Here's my code, i want to stream audio my tts stream. import asyncio import edgetts TEXT…
- User
Here's my code, i want to stream audio my tts stream.
import asyncio
import edge_tts
TEXT = "Hello World!" VOICE = "en-GB-SoniaNeural" OUTPUT_FILE = "test.mp3"
async def amain() -> None: """Main function""" communicate = edge_tts.Communicate(TEXT, VOICE) with open(OUTPUT_FILE, "wb") as file: async for chunk in communicate.stream(): if chunk["type"] == "audio": file.write(chunk["data"]) elif chunk["type"] == "WordBoundary": print(f"WordBoundary: {chunk}")
if name == "main": loop = asyncio.get_event_loop_policy().get_event_loop() try: loop.run_until_complete(amain()) finally: loop.close()
I found this code, inspire on it to do what i want on my the upper code :
import pyaudio import numpy as np from time import time,sleep import os
CHANNELS = 2 RATE = 44100
TT = time() freq = 100 newfreq = 100 phase = 0 log_file = "probemon.log"
def callback(in_data, frame_count, time_info, status): global TT,phase,freq,newfreq if newfreq != freq: phase = 2np.piTT*(freq-newfreq)+phase freq=newfreq left = (np.sin(phase+2np.pifreq*(TT+np.arange(frame_count)/float(RATE)))) data = np.zeros((left.shape[0]*2,),np.float32) data[0::2] = left #left data data[1::2] = left #right data TT+=frame_count/float(RATE) return (data, pyaudio.paContinue)
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paFloat32, channels=CHANNELS, rate=RATE, output=True, stream_callback=callback)
stream.start_stream() tmphold = "" try: while True: line = os.popen('tail -n 1 {}'.format(log_file)).read() try: key, val = line.split() except: key, val = "default", 0.0
f = abs(int(val)) newfreq = f * 10 #update freq per log if newfreq != tmphold: tmphold = newfreq print "mac:{} , rssi:{} , freq:{}finally: stream.stop_stream() stream.close() p.terminate()
- Assistant
To integrate the streaming audio capability from
edge_tts(text-to-speech stream) withpyaudiofor real-time playback, you would need to modify youramainfunction to directly write the audio data to the stream instead of saving it to a file. Additionally, you will have to handle the stream's sample format, channels, and rate properly to match 's output. - User
Edit my script by inspiring on this : import asyncio import edge_tts import wave import io
OUTPUT_FILE = "output.wav" SAMPLE_RATE = 44100 CHANNELS = 1 SAMPLE_WIDTH = 2 # 16-bit audio TEXT = "这里是语音流测试" VOICE = "Microsoft Server Speech Text to Speech Voice (zh-CN, XiaoxiaoNeural)"
async def _main() -> None: communicate = edge_tts.Communicate(TEXT, VOICE)
# Create a WAV file and write audio data with wave.open(OUTPUT_FILE, "wb") as wav_file: wav_file.setnchannels(CHANNELS) wav_file.setsampwidth(SAMPLE_WIDTH) wav_file.setframerate(SAMPLE_RATE) async for chunk in communicate.stream(): if chunk["type"] == "audio": audio_data = chunk["data"] # Convert the audio data to a file-like object using BytesIO audio_file = io.BytesIO(audio_data) # Write the raw audio data to the WAV file wav_file.writeframes(audio_file.read())if name == "main": asyncio.run(_main())
- Assistant
It appears that you're trying to create a script that receives text-to-speech (TTS) streams using and saves the output into a WAV file format. I have made a few corrections to the code snippet you provided. Here's the updated script based on the sample you shared:
- User
I want to stream play audio with wav instead of play
- Assistant
To stream and play the audio from the
edge_ttsoutput directly, without first writing it to a WAV file, you can leverage to handle the streaming audio playback. Here is how to modify your script to do this: - User
Looks like you don't understand, audio_segment = AudioSegment.from_file(BytesIO(chunk["data"]), format="mp3") converts to mp3 the chunks, you need to convert them to WAV
- Assistant
- User
Error processing audio chunk: mode must be 'r', 'rb', 'w', or 'wb'
- Assistant
- User
But the problem with mp3 it's that it let a void after each chunk, fix this!!!
- Assistant
- User
The gap is still there. PLEASE, please, just inspire on this :
This solution plays audio based on last line of log continuously until log data changes.
This solution also eliminated popping / cracking sound that occurs when merging two tones.
Inspiration from here.
import pyaudio import numpy as np from time import time,sleep import os
CHANNELS = 2 RATE = 44100
TT = time() freq = 100 newfreq = 100 phase = 0 log_file = "probemon.log"
def callback(in_data, frame_count, time_info, status): global TT,phase,freq,newfreq if newfreq != freq: phase = 2np.piTT*(freq-newfreq)+phase freq=newfreq left = (np.sin(phase+2np.pifreq*(TT+np.arange(frame_count)/float(RATE)))) data = np.zeros((left.shape[0]*2,),np.float32) data[0::2] = left #left data data[1::2] = left #right data TT+=frame_count/float(RATE) return (data, pyaudio.paContinue)
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paFloat32, channels=CHANNELS, rate=RATE, output=True, stream_callback=callback)
stream.start_stream() tmphold = "" try: while True: line = os.popen('tail -n 1 {}'.format(log_file)).read() try: key, val = line.split() except: key, val = "default", 0.0
- Assistant
- User
loop = asyncio.get_event_loop() Traceback (most recent call last): File "c:\Users\Brahim\Desktop\Python\WoW\TTS\tts-test4.py", line 74, in main() File "c:\Users\Brahim\Desktop\Python\WoW\TTS\tts-test4.py", line 56, in main loop.run_until_complete(stream_tts()) File "C:\Users\Brahim\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 664, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "c:\Users\Brahim\Desktop\Python\WoW\TTS\tts-test4.py", line 26, in stream_tts audio_segment = AudioSegment.from_file(BytesIO(chunk['data']), format="mp3") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Brahim\AppData\Local\Programs\Python\Python312\Lib\site-packages\pydub\audio_segment.py", line 773, in from_file raise CouldntDecodeError( pydub.exceptions.CouldntDecodeError: Decoding failed. ffmpeg returned error code: 4294967274
Output from ffmpeg/avlib:
- Assistant
The error message
pydub.exceptions.CouldntDecodeError: Decoding failed. ffmpeg returned error code: 4294967274suggests thatpydubis having trouble decoding the MP3 data, and this is often due to one of the following reasons: - User
Oh please, be smart. FFMPEG IS WORKING, YOU CODE IS NOT
- Assistant