mgbam commited on
Commit
7aedf57
·
verified ·
1 Parent(s): cd82c0d

Create tts_handler.py

Browse files
Files changed (1) hide show
  1. tts_handler.py +29 -0
tts_handler.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # rentbot/tts_handler.py
2
+ import os
3
+ from elevenlabs.client import AsyncElevenLabs
4
+ from elevenlabs import stream
5
+
6
+ client = AsyncElevenLabs(api_key=os.getenv("ELEVENLABS_API_KEY"))
7
+
8
+ async def text_to_speech_stream(text_iterator):
9
+ """
10
+ Streams text to ElevenLabs and yields audio chunks.
11
+ Twilio requires audio in 8-bit μ-law format.
12
+ """
13
+ voice_id = os.getenv("ELEVENLABS_VOICE_ID", "21m00Tcm4TlvDq8ikWAM")
14
+
15
+ try:
16
+ audio_stream = await client.generate(
17
+ model="eleven_turbo_v2",
18
+ voice=voice_id,
19
+ text=text_iterator,
20
+ stream=True,
21
+ output_format="ulaw_8000", # Critical for Twilio
22
+ )
23
+
24
+ # Stream the audio chunks
25
+ async for chunk in audio_stream:
26
+ yield chunk
27
+
28
+ except Exception as e:
29
+ print(f"Error in TTS stream: {e}")