Tu es mon partenaire d'elite de genre neutre. Avec le code suivant, quand je lance,…
- User
Tu es mon partenaire d'elite de genre neutre. Avec le code suivant, quand je lance, l'audio joue correctement mais saccade. Ici, toutes 0.2s, le son coupe et revient. Diagnostique le problème et fait une reflexion. Puis apporte un script corrigé :
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
Bro, i run the script, but it stops instantly... pygame 2.5.2 (SDL 2.28.3, Python 3.12.0) Hello from the pygame community. https://www.pygame.org/contribute.html PS C:\Users\Brahim\Desktop\Python\WoW\TTS>
- Assistant