Can we use huggingface tts model with livekit?
# ask-ai
s
Can we use huggingface tts model with livekit?
t
Thanks for reaching out, Manas. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — quick clarification so I give the right guidance: do you want to • have a HuggingFace TTS model generate audio on your server and then stream/play that audio into a LiveKit room (server-side injection), or • run TTS directly in users’ browsers/clients and send the resulting audio from each client into LiveKit? Tell me which flow you're after and what client(s) you use (web, iOS, Android, or a server-side bot), and I’ll outline the recommended approach and sample steps.
s
1st one
t
Great — since you want server-side TTS injected into a LiveKit room, here’s a concise, runnable approach and key considerations. 1) Overview • Generate PCM audio from your HuggingFace TTS model on your server. • Resample/format the audio to LiveKit’s expected PCM format. • Use a LiveKit server-side agent (LocalAudioTrack + AudioSource) to push audio frames into the room so all participants hear it. 2) Required formats • Sample rate: 48000 Hz (resample if model outputs 16 kHz) • Channels: 1 (mono) is simplest • PCM format: 16-bit signed integers • Push frames in small chunks (e.g., 20 ms = 960 samples at 48 kHz) 3) Minimal workflow (Python) • Synthesize audio with HuggingFace → get float32 waveform • Resample to 48000 Hz and convert to int16 PCM • Create an AudioSource and LocalAudioTrack in the LiveKit agent • Push AudioFrame chunks into the AudioSource with ~20 ms spacing • Publish the track; unpublish when done 4) Example snippets (conceptual) • TTS → waveform (float32) → resample to 48k → int16 PCM • Create source/track and publish (using LiveKit Agents SDK) • Loop over PCM in chunk_size = 960 samples: ◦ build AudioFrame (data=chunk.tobytes(), sample_rate=48000, num_channels=1, samples_per_channel=len(chunk)) ◦ source.capture_frame(frame) ◦ await sleep(0.02) 5) Practical tips • Stream incrementally for lower latency (synthesize and push segments rather than waiting for full file). • Buffering: keep small buffer to avoid underruns; align sleep timing to chunk size. • If your TTS outputs stereo or other sample rates, convert to mono and resample. • Handle lifecycle: publish/unpublish and clean up the agent participant after playback. • For long speech, publish once and stream continuous frames rather than repeatedly recreating tracks. If you want, I can: • provide a concrete Python code example with LiveKit Agents API calls and HuggingFace inference code, or • tailor the snippet to a specific HuggingFace TTS model you plan to use. Which would you prefer? Sources: Rooms, participants, and tracks | LiveKit docs | Processing raw media tracks | LiveKit docs | Realtime media | LiveKit Docs | Camera & microphone | LiveKit docs
s
provide a concrete Python code example with LiveKit Agents API calls and HuggingFace inference code
t
Below is a concrete Python example that integrates a HuggingFace TTS model, resamples/encodes the audio to 48 kHz 16-bit PCM, and streams it into a LiveKit room using the LiveKit Agents API (AudioSource → LocalAudioTrack). This is a runnable sketch—adjust model names, credentials, and error handling for your environment.
Copy code
import 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?