salmon-park-70324
12/02/2025, 9:35 AMtall-airline-16756
12/02/2025, 9:35 AMtall-airline-16756
12/02/2025, 9:36 AMsalmon-park-70324
12/02/2025, 9:37 AMtall-airline-16756
12/02/2025, 9:37 AMsalmon-park-70324
12/02/2025, 9:45 AMtall-airline-16756
12/02/2025, 9:45 AMimport os
import asyncio
import numpy as np
import soundfile as sf
import librosa
from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
# LiveKit Agents & RTC imports (based on provided examples)
from livekit import rtc
from livekit.agents import Agent, rtc_session
# Environment variables to set:
# LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, ROOM_NAME
# Adjust agent connection/auth as your deployment requires.
SAMPLE_RATE_OUT = 48000
CHANNELS = 1
CHUNK_MS = 20
CHUNK_SAMPLES = int(SAMPLE_RATE_OUT * (CHUNK_MS / 1000.0)) # 960 samples for 20ms
# --------- HuggingFace TTS setup (SpeechT5 example) ----------
processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
tts_model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
async def synthesize_text_to_pcm16(text: str, orig_sr: int = 16000):
"""
Returns int16 numpy array at SAMPLE_RATE_OUT (48000) mono.
Uses SpeechT5 model + HiFi-GAN vocoder as an example.
"""
inputs = processor(text=text, return_tensors="pt")
# Generate waveform (float32) at model's output sample rate (often 16k)
speech = tts_model.generate_speech(inputs["input_ids"], vocoder=vocoder)
waveform = speech.numpy().squeeze() # float32, shape (N,)
# If model output sample rate differs, resample to SAMPLE_RATE_OUT
if orig_sr != SAMPLE_RATE_OUT:
waveform = librosa.resample(waveform, orig_sr=orig_sr, target_sr=SAMPLE_RATE_OUT)
# Ensure mono
if waveform.ndim > 1:
waveform = np.mean(waveform, axis=0)
# Normalize/clamp and convert to int16 PCM
waveform = waveform / np.max(np.abs(waveform) + 1e-9)
pcm16 = (waveform * 32767).astype(np.int16)
return pcm16
# --------- LiveKit Agent + streaming logic ----------
class TtsAgent(Agent):
@rtc_session
async def run(self, local_participant: rtc.LocalParticipant, **kwargs):
# Create AudioSource and LocalAudioTrack
source = rtc.AudioSource(SAMPLE_RATE_OUT, CHANNELS)
track = rtc.LocalAudioTrack.create_audio_track("tts-audio", source)
await local_participant.publish_track(track, rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_MICROPHONE))
try:
# Example text to synthesize
text = "Hello, this is a test from the TTS agent."
pcm = await synthesize_text_to_pcm16(text, orig_sr=16000)
# Stream PCM in CHUNK_SAMPLES frames with ~CHUNK_MS spacing
for i in range(0, len(pcm), CHUNK_SAMPLES):
chunk = pcm[i:i + CHUNK_SAMPLES]
# If last chunk shorter than CHUNK_SAMPLES, pad with zeros
if len(chunk) < CHUNK_SAMPLES:
pad = np.zeros(CHUNK_SAMPLES - len(chunk), dtype=np.int16)
chunk = np.concatenate([chunk, pad])
frame = rtc.AudioFrame(
data=chunk.tobytes(),
sample_rate=SAMPLE_RATE_OUT,
num_channels=CHANNELS,
samples_per_channel=len(chunk)
)
await source.capture_frame(frame)
await asyncio.sleep(CHUNK_MS / 1000.0)
finally:
# Clean up: unpublish and stop track
await local_participant.unpublish_track(track)
# --------- Run agent (example entrypoint) ----------
if __name__ == "__main__":
# Agent config is typically handled by LiveKit Agents framework/environment.
# This will vary by deployment; ensure LIVEKIT_* env vars are set.
agent = TtsAgent()
agent.run_forever()
Notes and adjustments you may need:
• Replace the SpeechT5 model/vocoder names if you use a different HuggingFace TTS model. Ensure you know the model's native sample rate (orig_sr) and set it correctly when resampling.
• The example assumes mono output. If your model returns stereo, mix to mono or set CHANNELS=2 and adapt frame creation.
• Tune buffering and sleep timing for smoother playback in your environment.
• Add error handling and logging for production use.
• If your LiveKit Agents framework requires different initialization or auth, adapt the agent bootstrap accordingly.
Would you like this adapted to a different HuggingFace TTS model or to output stereo?