Adapt this script to my needs, i want a function to generate and play sound, in main i…
- User
Adapt this script to my needs, i want a function to generate and play sound, in main i want 4 test audio played, i want to be able to stop every audio to play new audio too : import asyncioimport pyaudiofrom io import BytesIOfrom pydub import AudioSegmentimport edge_ttsTEXT = "Hello World! How are you today, I’m super good!" * 25VOICE = "en-GB-SoniaNeural"async def main():# Initialize PyAudiop = pyaudio.PyAudio()stream = None# Create a container for the full audio datafull_audio_data = bytearray()# Fetch audio data from edge_ttscommunicate = edge_tts.Communicate(TEXT, VOICE)async for chunk in communicate.stream():if chunk["type"] == "audio":# Directly append MP3 audio datafull_audio_data.extend(chunk["data"])elif chunk["type"] == "WordBoundary":print(f"WordBoundary: {chunk}")if full_audio_data:# Convert the full audio data from MP3 to WAV onceaudio_segment = AudioSegment.from_file(BytesIO(full_audio_data), format="mp3")raw_data = audio_segment.raw_data# Open a single stream with the correct audio propertiesstream = p.open(format=p.get_format_from_width(audio_segment.sample_width),channels=audio_segment.channels,rate=audio_segment.frame_rate,output=True)# Stream the audiostream.write(raw_data)# Stop and close the streamstream.stop_stream()stream.close()# Terminate the PyAudio instancep.terminate()if name == "main":asyncio.run(main())
- Assistant
- User
I modified the following script, do the modifications. Also, I would like if a audio is playing and i want to play another audio, i want to be able to stop and play the new audio : async def generate_and_play_sound(text, voice, speed = 0, pitch = 0, volume = 0): global stream, p
code# If a stream is active, stop and close it if stream is not None and not stream.is_stopped(): stream.stop_stream() stream.close() full_audio_data = bytearray() # Fetch audio data from edge_tts communicate = edge_tts.Communicate(text, voice, rate = format_percent(speed), pitch = format_pitch(pitch), volume = format_percent(volume)) async for chunk in communicate.stream(): if chunk["type"] == "audio": full_audio_data.extend(chunk["data"]) if full_audio_data: audio_segment = AudioSegment.from_file(BytesIO(full_audio_data), format="mp3") raw_data = audio_segment.raw_data stream = p.open(format=p.get_format_from_width(audio_segment.sample_width), channels=audio_segment.channels, rate=audio_segment.frame_rate, output=True) stream.write(raw_data) - Assistant