The following script plays the audio correctly, but it stops and continue every 0.1s…
- User
The following script plays the audio correctly, but it stops and continue every 0.1s because of await asyncio.sleep(0.01). I WANT IT TO BE SMOOTLY, WITH NO STOP. Find the best working solution and fix the code
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
Now the audio is just not played, when i start the script it ends directly
- Assistant