协作头脑风暴
brainstorming
在实现前澄清需求、探索设计选择,并形成清晰的开发方向。
elevenlabs【开发与工程】AI-powered audio generation using ElevenLabs API - text-to-speech with lifelike voices, sound effects generation, and music creation from text descriptions. Generate natural-sounding speech in 32 languages, create custom sound effects for games and videos, and compose royalty-free music tracks. Use this skill when the user requests: - Voice generati…
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: elevenlabs description: | AI-powered audio generation using ElevenLabs API - text-to-speech with lifelike voices, sound effects generation, and music creation from text descriptions. Generate natural-sounding speech in 32 languages, create custom sound effects for games and videos, and compose royalty-free music tracks.
Use this skill when the user requests:
Capabilities: Text-to-speech (32 languages, 100+ voices), sound effects generation, music composition, voice cloning, real-time audio streaming
This skill enables AI-powered audio generation through ElevenLabs API. Create lifelike text-to-speech in 32 languages, generate custom sound effects for games and videos, and compose royalty-free music from text descriptions. Support for 100+ professional voices, custom voice cloning, real-time streaming, and multi-speaker dialogue.
This skill should be invoked when the user asks to:
Models:
eleven_multilingual_v2) - Highest quality, 29 languageseleven_flash_v2_5) - Ultra-low 75ms latency, 32 languages, 50% cheapereleven_turbo_v2_5) - Balanced quality and latencyFeatures:
Output Formats:
Model:
eleven_text_to_sound_v2)Features:
Use Cases:
Features:
Parameters:
Requirements:
Content Policy:
Analyze the user's request to determine:
For Text-to-Speech:
eleven_multilingual_v2eleven_flash_v2_5eleven_turbo_v2_5For Sound Effects:
eleven_text_to_sound_v2 modelFor Music:
import os
from elevenlabs.client import ElevenLabs
# Initialize client with API key
client = ElevenLabs(api_key=os.environ.get("ELEVENLABS_API_KEY"))
API key should be set as environment variable:
export ELEVENLABS_API_KEY="your-api-key-here"
Basic Speech Generation:
from elevenlabs.client import ElevenLabs
from pathlib import Path
client = ElevenLabs(api_key=os.environ["ELEVENLABS_API_KEY"])
# Generate speech
audio = client.text_to_speech.convert(
text="Your text content here",
voice_id="JBFqnCBsd6RMkjVDRZzb", # Default voice (George)
model_id="eleven_multilingual_v2",
output_format="mp3_44100_128"
)
# Save to file
output_path = Path("speech_output.mp3")
with output_path.open("wb") as f:
for chunk in audio:
f.write(chunk)
print(f"Audio saved to: {output_path}")
Streaming Speech (Real-time):
from elevenlabs.client import ElevenLabs
from elevenlabs import stream
client = ElevenLabs(api_key=os.environ["ELEVENLABS_API_KEY"])
# Stream audio in real-time
audio_stream = client.text_to_speech.convert_as_stream(
text="This will be streamed as it generates",
voice_id="JBFqnCBsd6RMkjVDRZzb",
model_id="eleven_flash_v2_5", # Low latency model for streaming
output_format="mp3_44100_128"
)
# Stream to speakers
stream(audio_stream)
Multi-Speaker Dialogue:
# Generate conversation with multiple voices
speakers = [
{
"voice_id": "JBFqnCBsd6RMkjVDRZzb", # Speaker 1
"text": "Hello, how are you today?"
},
{
"voice_id": "21m00Tcm4TlvDq8ikWAM", # Speaker 2 (Rachel)
"text": "I'm doing great, thanks for asking!"
}
]
# Generate each speaker's audio and combine
from pydub import AudioSegment
combined = AudioSegment.empty()
for speaker in speakers:
audio = client.text_to_speech.convert(
text=speaker["text"],
voice_id=speaker["voice_id"],
model_id="eleven_multilingual_v2"
)
# Save temp file
temp_path = Path(f"temp_{speaker['voice_id']}.mp3")
with temp_path.open("wb") as f:
for chunk in audio:
f.write(chunk)
# Add to combined audio
segment = AudioSegment.from_mp3(str(temp_path))
combined += segment
temp_path.unlink() # Clean up
# Export final dialogue
combined.export("dialogue.mp3", format="mp3")
List Available Voices:
# Get all available voices
voices = client.voices.get_all()
print("Available voices:")
for voice in voices.voices:
print(f"- {voice.name} (ID: {voice.voice_id})")
print(f" Labels: {voice.labels}")
print(f" Description: {voice.description}")
Common Voice IDs:
JBFqnCBsd6RMkjVDRZzb - George (male, English, middle-aged)21m00Tcm4TlvDq8ikWAM - Rachel (female, English, young)AZnzlk1XvdvUeBnXmlld - Domi (female, English, young)EXAVITQu4vr4xnSDxMaL - Bella (female, English, young)ErXwobaYiN019PkySvjV - Antoni (male, English, young)MF3mGyEYCl7XYWbV9V6O - Elli (female, English, young)TxGEqnHWrfWFTfGW9XjX - Josh (male, English, young)Basic Sound Effect Generation:
from elevenlabs.client import ElevenLabs
from pathlib import Path
client = ElevenLabs(api_key=os.environ["ELEVENLABS_API_KEY"])
# Generate sound effect
audio = client.text_to_sound_effects.convert(
text="footsteps on wooden floor, slow paced walking",
duration_seconds=5.0,
prompt_influence=0.5 # How closely to follow prompt (0.0-1.0)
)
# Save to file
output_path = Path("footsteps.mp3")
with output_path.open("wb") as f:
for chunk in audio:
f.write(chunk)
print(f"Sound effect saved to: {output_path}")
Looping Sound Effect:
# Generate seamlessly looping audio
audio = client.text_to_sound_effects.convert(
text="gentle rain falling on leaves, ambient nature sound",
duration_seconds=10.0,
prompt_influence=0.5
# Note: loop parameter may be available in newer API versions
)
output_path = Path("rain_loop.mp3")
with output_path.open("wb") as f:
for chunk in audio:
f.write(chunk)
Multiple Sound Effects:
# Generate various sound effects for a game
sound_effects = [
{
"name": "explosion",
"description": "large explosion, debris falling, action movie style",
"duration": 3.0
},
{
"name": "door_open",
"description": "creaky wooden door slowly opening, horror atmosphere",
"duration": 2.0
},
{
"name": "ui_click",
"description": "soft button click, UI feedback sound, pleasant tone",
"duration": 0.5
}
]
for sfx in sound_effects:
audio = client.text_to_sound_effects.convert(
text=sfx["description"],
duration_seconds=sfx["duration"]
)
output_path = Path(f"{sfx['name']}.mp3")
with output_path.open("wb") as f:
for chunk in audio:
f.write(chunk)
print(f"Generated: {output_path}")
Basic Music Composition:
from elevenlabs.client import ElevenLabs
from pathlib import Path
client = ElevenLabs(api_key=os.environ["ELEVENLABS_API_KEY"])
# Generate music from prompt
prompt = """Upbeat indie pop song with acoustic guitar, light drums, and cheerful
melody. Modern and energetic feel, perfect for background music in a lifestyle video.
Instrumental only, no vocals."""
try:
audio = client.music_generation.compose(
prompt=prompt,
music_length_ms=30000 # 30 seconds
)
# Save music file
output_path = Path("background_music.mp3")
with output_path.open("wb") as f:
for chunk in audio:
f.write(chunk)
print(f"Music saved to: {output_path}")
except Exception as e:
if "paid" in str(e).lower() or "subscription" in str(e).lower():
print("Error: Music generation requires a paid ElevenLabs account")
else:
print(f"Error: {e}")
Music with Composition Plan:
# Create structured composition plan first
composition_plan = client.music_generation.composition_plan.create(
prompt="""Electronic dance music track with energetic build-up, drop section,
and chill outro. Progressive house style.""",
music_length_ms=60000 # 60 seconds
)
# Generate music from plan (allows for more control)
audio = client.music_generation.compose(
composition_plan=composition_plan
)
output_path = Path("edm_track.mp3")
with output_path.open("wb") as f:
for chunk in audio:
f.write(chunk)
Genre-Specific Music:
# Generate music for different genres/moods
music_prompts = {
"cinematic": """Epic cinematic orchestral music with dramatic strings, powerful
brass, and heroic theme. Perfect for movie trailer, inspiring and grand.""",
"lo-fi": """Chill lo-fi hip hop beats with jazz piano, vinyl crackle, and mellow
drums. Relaxing study music atmosphere, instrumental.""",
"ambient": """Ambient soundscape with ethereal pads, subtle textures, and peaceful
atmosphere. Meditative and calming, perfect for relaxation.""",
"game_menu": """Mysterious fantasy game menu music with harp, soft strings, and
magical atmosphere. Medieval RPG feel, looping background music."""
}
for name, prompt in music_prompts.items():
try:
audio = client.music_generation.compose(
prompt=prompt,
music_length_ms=20000 # 20 seconds
)
output_path = Path(f"music_{name}.mp3")
with output_path.open("wb") as f:
for chunk in audio:
f.write(chunk)
print(f"Generated: {output_path}")
except Exception as e:
print(f"Error generating {name}: {e}")
Save Audio Files:
from pathlib import Path
def save_audio(audio_generator, filename):
"""Save audio generator to file"""
output_path = Path(filename)
with output_path.open("wb") as f:
for chunk in audio_generator:
f.write(chunk)
print(f"Saved: {output_path.absolute()}")
return output_path
Error Handling:
import os
from elevenlabs.client import ElevenLabs
def check_api_key():
"""Verify API key is set"""
if not os.environ.get("ELEVENLABS_API_KEY"):
raise ValueError(
"ELEVENLABS_API_KEY not set. "
"Please set environment variable: export ELEVENLABS_API_KEY='your-key'"
)
def handle_elevenlabs_request(func, *args, **kwargs):
"""Wrapper for error handling"""
try:
return func(*args, **kwargs)
except Exception as e:
error_msg = str(e).lower()
if "api key" in error_msg or "authentication" in error_msg:
print("Error: Invalid or missing API key")
print("Set your API key: export ELEVENLABS_API_KEY='your-key'")
elif "quota" in error_msg or "limit" in error_msg:
print("Error: API quota exceeded")
print("Check your usage at https://elevenlabs.io/app/usage")
elif "paid" in error_msg or "subscription" in error_msg:
print("Error: This feature requires a paid subscription")
elif "bad_prompt" in error_msg:
print("Error: Prompt contains restricted content")
print("Avoid copyrighted material (artist names, brands)")
else:
print(f"Error: {e}")
raise
API Key:
ELEVENLABS_API_KEYPython Packages:
pip install elevenlabs pydub python-dotenv
System:
Account Requirements:
Choose Appropriate Model:
eleven_multilingual_v2eleven_flash_v2_5eleven_turbo_v2_5Select Right Voice:
voices.get_all() to explore optionsOptimize for Use Case:
Format Selection:
Be Descriptive:
Duration Control:
Prompt Influence:
Iteration:
Detailed Prompts:
Avoid Copyrighted References:
Duration Planning:
Composition Plans:
API Key Security:
.env files for local developmentError Handling:
Cost Optimization:
File Management:
Testing:
User request: "Convert this chapter to audiobook format"
Expected behavior:
eleven_multilingual_v2)audio = client.text_to_speech.convert(
text=chapter_text,
voice_id="JBFqnCBsd6RMkjVDRZzb", # George
model_id="eleven_multilingual_v2",
output_format="mp3_44100_128"
)
save_audio(audio, "chapter_1.mp3")
User request: "Generate sound effects for a fantasy RPG game"
Expected behavior:
sfx_list = [
("sword_swing", "sword whooshing through air, fantasy combat", 1.0),
("potion_drink", "drinking magical potion, gulp sound, RPG game", 0.8),
("spell_cast", "magical spell casting, ethereal whoosh, fantasy magic", 1.5),
("footsteps_stone", "footsteps on stone dungeon floor, echoing", 2.0)
]
for name, description, duration in sfx_list:
audio = client.text_to_sound_effects.convert(
text=description,
duration_seconds=duration
)
save_audio(audio, f"sfx_{name}.mp3")
User request: "Create a podcast intro with voice and background music"
Expected behavior:
# Generate intro speech
intro_text = "Welcome to the Tech Talk podcast, where we discuss the latest in technology and innovation."
speech = client.text_to_speech.convert(
text=intro_text,
voice_id="TxGEqnHWrfWFTfGW9XjX", # Josh (energetic)
model_id="eleven_flash_v2_5"
)
save_audio(speech, "podcast_intro_voice.mp3")
# Generate background music (requires paid account)
music = client.music_generation.compose(
prompt="Upbeat tech podcast intro music, electronic beats, modern and energetic",
music_length_ms=10000 # 10 seconds
)
save_audio(music, "podcast_intro_music.mp3")
print("Use audio editing software to mix voice and music")
User request: "Create welcome messages in English, Spanish, and French"
Expected behavior:
messages = {
"english": ("Hello and welcome!", "JBFqnCBsd6RMkjVDRZzb"),
"spanish": ("¡Hola y bienvenido!", "ThT5KcBeYPX3keUQqHPh"), # Spanish voice
"french": ("Bonjour et bienvenue!", "XB0fDUnXU5powFXDhCwa") # French voice
}
for lang, (text, voice_id) in messages.items():
audio = client.text_to_speech.convert(
text=text,
voice_id=voice_id,
model_id="eleven_multilingual_v2"
)
save_audio(audio, f"welcome_{lang}.mp3")
User request: "Stream this news article as audio"
Expected behavior:
from elevenlabs import stream
audio_stream = client.text_to_speech.convert_as_stream(
text=news_article_text,
voice_id="21m00Tcm4TlvDq8ikWAM", # Rachel
model_id="eleven_flash_v2_5",
output_format="mp3_44100_128"
)
# Stream to speakers in real-time
stream(audio_stream)
Music Generation:
API Quotas:
Voice Cloning:
Audio Quality:
Language Support:
Sound Effects:
Content Policy:
image-generation - For visual content creationpython-plotting - For visualizing audio datascientific-writing - For generating narration textpython-best-practices - For writing clean audio processing code