My apologies for the confusion. It seems there was a misunderstanding and I provided a snippet that might not be correctly implementing the audio playback.
The 'clack clack' noise could indeed be the result of writing incomplete frames to the stream. To resolve this, let's revise the code to ensure that the audio data from each chunk is being correctly decoded and written to the PyAudio stream. This involves using the pydub library to decode the MP3 data and extract the raw audio as PCM format.
Here is an updated code snippet that should help eliminate the 'clack clack' noise by streamlining the audio decoding and playback process:
import pyaudio
from pydub import AudioSegment
from io import BytesIO
import asyncio
# Example TTS communication stub in case 'edge_tts' is not defined.
class Communicate:
async def stream(self):
# This should be replaced with actual streaming from TTS service
for _ in range(10):
yield {"type": "audio", "data": b'...'} # Byte data for audio chunk
await asyncio.sleep(0.1)
# Placeholder function for formatting values
def format_percent(value):
# Replace this function with actually processing the input
return value
def format_pitch(value):
# Replace this function with actually processing the input
return value
# Global PyAudio instance
p = pyaudio.PyAudio()
async def generate_and_play_sound(text, voice, speed=0, pitch=0, volume=0):
# Initialize the audio stream with increased buffer size and settings
stream = p.open(
format=p.get_format_from_width(2), # 16-bit audio
channels=1, # Mono audio
rate=24000, # Sample rate
output=True,
frames_per_buffer=4096 # Increase buffer size if needed
)
# Fetch audio data from TTS service
# This is where you'd use 'edge_tts.Communicate' or similar TTS streaming API.
communicate = Communicate() # Replace with actual TTS service API call
# Process and play audio chunks as they arrive
async for chunk in communicate.stream():
if chunk["type"] == "audio":
try:
# Decode the MP3 chunk data to raw PCM audio format and play it
audio_segment = AudioSegment.from_file(BytesIO(chunk["data"]), format="mp3")
stream.write(audio_segment.raw_data, len(audio_segment.raw_data))
except Exception as e:
print("Error processing audio chunk:", e)
# End and close the stream once all audio has been played
stream.stop_stream()
stream.close()
async def main():
# Example usage
await generate_and_play_sound("Hello world!", "VoiceName")
# Run the main function if this script is executed
if __name__ == '__main__':
asyncio.run(main())
Note the '...' in the stream method of the Communicate stub class should be replaced with the actual MP3 audio data received from the TTS engine.
Please replace the Communicate class with your actual TTS streaming implementation. Also, note that format_percent() and format_pitch() are placeholders for functions that should properly process the speed, pitch, and volume to be suitable for the TTS engine. Adjust these parts of the code so that they fit into your overall solution.
If you continue to experience issues, ensure the audio data is intact, the correct sample rate is used to match the TTS engine output, and you have the 'pydub' library installed and properly configured to decode the MP3 data.