File size: 864 Bytes
7aedf57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# rentbot/tts_handler.py
import os
from elevenlabs.client import AsyncElevenLabs
from elevenlabs import stream

client = AsyncElevenLabs(api_key=os.getenv("ELEVENLABS_API_KEY"))

async def text_to_speech_stream(text_iterator):
    """
    Streams text to ElevenLabs and yields audio chunks.
    Twilio requires audio in 8-bit μ-law format.
    """
    voice_id = os.getenv("ELEVENLABS_VOICE_ID", "21m00Tcm4TlvDq8ikWAM")
    
    try:
        audio_stream = await client.generate(
            model="eleven_turbo_v2",
            voice=voice_id,
            text=text_iterator,
            stream=True,
            output_format="ulaw_8000", # Critical for Twilio
        )
        
        # Stream the audio chunks
        async for chunk in audio_stream:
            yield chunk
            
    except Exception as e:
        print(f"Error in TTS stream: {e}")