I found this super code on the internet. I want to implement it to my script. The script…
- User
I found this super code on the internet. I want to implement it to my script. The script i want to make is a TTS that stream play audio smoothly. Code I found on internet :
ing callback, which allows manipulating stream data while its being played in realtime.
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
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()
My script, it plays audio but there is void between chunks of audio which is not good :
import asyncio import edge_tts import pyaudio from io import BytesIO from pydub import AudioSegment
TEXT = “aHello World!” VOICE = “en-GB-SoniaNeural”
p = pyaudio.PyAudio()
async def stream_tts(text: str, voice: str) -> None:
We’re assuming a certain format, channels, and rate
This will need to be dynamic based on the actual audio data from TTS
stream = p.open( format=pyaudio.paInt16, channels=1, rate=26000, output=True )
communicate = edge_tts.Communicate(text, voice)
This will act as our chunk size
chunk_size = 1024
Process and play audio chunks as they arrive
async for chunk in communicate.stream(): if chunk[“type”] == “audio”: try: audio_segment = AudioSegment.from_file(BytesIO(chunk[“data”]), format=“mp3”)
Write data to the stream directly without extra buffering
stream.write(audio_segment.raw_data)
If this is the last chunk, break after playing
if chunk.get(‘end’, False): break except Exception as e: print(“Error processing audio chunk:”, e)
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.