Your code is asynchronously fetching audio chunks from edge_tts and attempting to play them as they arrive. It seems the issue you're experiencing may be related to starting and stopping the audio stream within the loop, which might not be synchronized with the arrival of audio chunks. Additionally, the except block with print("woot") is not informative for debugging purposes.
Let's try to refactor the code to accumulate the entire audio data in the full_audio_data before playing it through the PyAudio stream. This will prevent the PyAudio stream from starting and stopping in an unsynchronized manner.
Here is an updated version of the function that accumulates the entire audio data first, and then plays it in one go:
import asyncio
import pyaudio
import edge_tts
from io import BytesIO
from pydub import AudioSegment
# Global PyAudio instance
p = pyaudio.PyAudio()
# Stream handle
stream = None
def format_percent(value):
return f"{value}%"
def format_pitch(value):
return f"{value}st"
async def generate_and_play_sound(text, voice, speed=0, pitch=0, volume=0):
global stream, p
# If a stream is active, stop and close it
if stream is not None and not stream.is_stopped():
stream.stop_stream()
stream.close()
stream = None
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":
try:
audio_segment = AudioSegment.from_file(BytesIO(chunk["data"]), format="mp3")
full_audio_data.extend(audio_segment.raw_data)
except Exception as e:
print(f"Error processing audio chunk: {e}")
if full_audio_data:
try:
# Convert the byte array to an AudioSegment
audio_segment = AudioSegment(
data=bytes(full_audio_data),
sample_width=2, # You might need to adjust this based on the delivered audio format
frame_rate=16000, # You might need to adjust this based on the delivered audio rate
channels=1 # You might need to adjust this for mono/stereo channels
)
stream = p.open(format=p.get_format_from_width(audio_segment.sample_width),
channels=audio_segment.channels,
rate=audio_segment.frame_rate,
output=True)
# Play the accumulated audio data
stream.write(full_audio_data)
stream.stop_stream()
stream.close()
stream = None
except Exception as e:
print(f"Error playing audio: {e}")
# Be sure to define the variables for text, voice, speed, pitch, and volume
# For example:
text = "Hello, world!"
voice = "en-US-JessaRUS" # Example voice name, this will need to match what edge_tts expects
# Then call the function with:
asyncio.run(generate_and_play_sound(text, voice))
Note that in this code, we create an AudioSegment assuming specific properties such as sample width, frame rate, and channels, which might need to be adjusted based on the actual audio data that is delivered.
Make sure to handle correct sample width, frame rate, and channels dynamically if necessary, as hardcoding them might result in incorrect playback depending on the specifics of the audio data received from edge_tts.
Finally, be aware that using asyncio.run() isn't recommended in a Jupyter Notebook or in an environment where an event loop is already running. Instead, you should use await to call the coroutine from an existing async function or loop.