音乐流式传输

本指南介绍如何使用 Music API 流式传输音乐。

操作指南 · 假设你已完成音乐 快速入门。

Music API 仅面向付费用户开放。

使用 Music API

本指南假设你已设置 API 密钥和 SDK。如尚未完成,请先完成 快速入门。

1

发起 API 请求

根据所选语言,新建名为 example.py 或 example.mts 的文件,并添加以下代码:

# example.py
from elevenlabs.client import ElevenLabs
from elevenlabs.play import play
import os
from io import BytesIO
from dotenv import load_dotenv
load_dotenv()
elevenlabs = ElevenLabs(
api_key=os.getenv("ELEVENLABS_API_KEY"),
)
stream = elevenlabs.music.stream(
prompt="Create an intense, fast-paced electronic track for a high-adrenaline video game scene. Use driving synth arpeggios, punchy drums, distorted bass, glitch effects, and aggressive rhythmic textures. The tempo should be fast, 130–150 bpm, with rising tension, quick transitions, and dynamic energy bursts.",
music_length_ms=10000,
model_id="music_v2_5",
)
# Create a BytesIO object to hold the audio data in memory
audio_stream = BytesIO()
# Write each chunk of audio data to the stream
for chunk in stream:
if chunk:
audio_stream.write(chunk)
# Reset stream position to the beginning
audio_stream.seek(0)
play(audio_stream)
2

执行代码

python example.py

你应该会听到生成的音乐开始播放。

后续步骤