Hello there, I've been trying to implement fast audio streaming for 6 days now, but I…
- User
Hello there,
I've been trying to implement fast audio streaming for 6 days now, but I just can't do it. Indeed, without the stream method, the save function of edge-tts takes about 1-2s to generate depending the text, which is too long.
In my code bellow, the audio is indeed played instantly, regardless of text size, but there are artefacts between chunks, like tiny spaces.
Do you know how to do audio streaming correctly please ? Thank you!
import asyncio import edge_tts import pyaudio from io import BytesIO from pydub import AudioSegment
TEXT = "Hello World!" VOICE = "en-GB-SoniaNeural"
p = pyaudio.PyAudio()
async def stream_tts(text: str, voice: str) -> None:
We're assuming a certain format, channels, and rate
This will need to be dynamic based on the actual audio data from TTS
stream = p.open( format=pyaudio.paInt16, channels=1, rate=26000, output=True )
communicate = edge_tts.Communicate(text, voice)
Process and play audio chunks as they arrive
async for chunk in communicate.stream(): if chunk["type"] == "audio": try: audio_segment = AudioSegment.from_file(BytesIO(chunk["data"]), format="mp3")
# Write data to the stream directly without extra buffering stream.write(audio_segment.raw_data) # If this is the last chunk, break after playing if chunk.get('end', False): break except Exception as e: print("Error processing audio chunk:", e)Cleanup
stream.stop_stream() stream.close() p.terminate() if name == "main":
Run the asyncio event loop
asyncio.run(stream_tts(TEXT, VOICE))
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.