-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathElevenLabs_Example.py
More file actions
80 lines (58 loc) · 2.86 KB
/
Copy pathElevenLabs_Example.py
File metadata and controls
80 lines (58 loc) · 2.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
🚀 This code demonstrates how to run the ElevenLabs API from Python.
📌 Setup Instructions:
1. Activate your Python environment (e.g., venv, conda, etc.).
2. Install ElevenLabs SDK using:
pip install elevenlabs
👨💻 Author: Dr. Wissam Jassim
📧 Email: wissam.a.jassim@gmail.com
🔗 ElevenLabs Python SDK: https://github.com/elevenlabs/elevenlabs-python
"""
from elevenlabs.client import ElevenLabs
from elevenlabs.play import play
from io import BytesIO
# 🔑 Define your ElevenLabs API key (replace with your actual key)
API_KEY = "YOUR_API_KEY"
# Create a client instance once for reuse
client = ElevenLabs(api_key=API_KEY)
def generate_and_play(text: str,
voice_id: str = "Xb7hH8MSUJpSbSDYk0k2",
model_id: str = "eleven_multilingual_v2",
save_path: str = "output.mp3"):
"""
Generate speech from text using ElevenLabs API, play it, and save it to a file.
Args:
text (str): The text to convert into speech.
voice_id (str, optional): The ElevenLabs voice ID to use. Defaults to "Xb7hH8MSUJpSbSDYk0k2".
model_id (str, optional): The ElevenLabs model ID to use. Defaults to "eleven_multilingual_v2".
save_path (str, optional): File path to save the generated audio. Defaults to "output.mp3".
"""
# Request text-to-speech conversion (audio comes in chunks/streamed)
audio = client.text_to_speech.convert(
text=text,
voice_id=voice_id,
model_id=model_id,
output_format="mp3_44100_128", # MP3 format, 44.1kHz, 128 kbps
)
# Create an in-memory buffer to collect audio chunks
audio_stream = BytesIO()
# Write each received audio chunk into the buffer
for chunk in audio:
if chunk: # Only write non-empty chunks
audio_stream.write(chunk)
# Get the complete audio as bytes
audio_bytes = audio_stream.getvalue()
# ▶️ Play the generated audio directly
play(audio_bytes)
# 💾 Save the audio to a file
with open(save_path, "wb") as f:
f.write(audio_bytes)
print(f"✅ Audio saved to {save_path}")
if __name__ == "__main__":
# Example usage: you can change this to any text you want
user_text = "Welcome to my YouTube channel! If you like this video, please give it a like and subscribe to get more videos."
# Example in Arabic (uncomment to test multilingual support):
# user_text = "مرحباً بكم في قناتي على اليوتيوب! إذا أعجبكم هذا الفيديو، يرجى الاشتراك بالقناة لمتابعة المزيد من الفيديوهات."
# Or ask user input (uncomment to enable interactive mode):
# user_text = input("Enter the text to convert to speech: ")
generate_and_play(user_text)