Modify this script, I want to play the audio in stream. Currently it's not the case, in…
- User
Modify this script, I want to play the audio in stream. Currently it's not the case, in the played audio there is a break between each chunk. Study how audio streaming is bestly made in python and make my script better : import asyncio from io import BytesIO import edge_tts import pygame from queue import Queue from pydub import AudioSegment
TEXT = "Hello World! How are you today, i'm super good !"*25 VOICE = "en-GB-SoniaNeural" CHUNK_SIZE = 1024 # Define the size of each audio chunk
Initialize Pygame Mixer
pygame.mixer.init(44100, -16, 2, 64)
Create a queue to hold audio chunks
audio_queue = Queue()
async def audio_consumer(): """Continuously play audio chunks as they become available.""" while True: if not audio_queue.empty(): chunk = audio_queue.get() # Convertir l'audio MP3 en données WAV en mémoire audio_data = AudioSegment.from_file(BytesIO(chunk), format="mp3") wav_bytes = BytesIO() audio_data.export(wav_bytes, format="wav") wav_bytes.seek(0) # Important pour remettre le curseur au début du BytesIO # Jouer l'audio directement à partir de la mémoire sound = pygame.mixer.Sound(file=wav_bytes) sound.play() await asyncio.sleep(0.01) # Sleep briefly to yield control to the event loop
async def amain(): """Main function to stream audio and put it into the queue.""" communicate = edge_tts.Communicate(TEXT, VOICE) async for chunk in communicate.stream(): if chunk["type"] == "audio": audio_queue.put(chunk["data"]) elif chunk["type"] == "WordBoundary": print(f"WordBoundary: {chunk}")
Run both the consumer and the main coroutine concurrently
async def main(): await asyncio.gather( amain(), audio_consumer() )
if name == "main": loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) finally: loop.close()
- Assistant
- User
During the sound play, it looks like it's speed up, and there is clack clack between each chunk
- Assistant
- User
Now there is no sound.......
- Assistant
- User
Okay, it works! But there is the clack clack effect all along the audio play
- Assistant
- User
It's WORSE!!!!!!!
- Assistant
- User
You're out of track, here's the working code with audio which have the clack clack effect during all the audio. Fix it : import asyncio import pyaudio from io import BytesIO from pydub import AudioSegment from queue import Queue import threading import edge_tts
TEXT = "Hello World! How are you today, I’m super good!" * 25 VOICE = "en-GB-SoniaNeural" CHUNK_SIZE = 1024 # Define the size of each audio chunk
- Assistant
The "clack clack" sound may be caused by abrupt transitions between audio chunks. To mitigate this, one strategy is to decode the entire audio first and then stream it to
pyaudio. This way, any potential decoding artifacts only occur once, and you are guaranteed to stream smooth audio data to the sound card.