How to implement custom TTS (murf ai streaming tts...
# ask-ai
a
How to implement custom TTS (murf ai streaming tts) in my existing LiveKit stt/llm/tts pipeline...
t
I'm glad you're looking to integrate Murf AI streaming TTS into your LiveKit STT/LLM/TTS pipeline! You have two friendly options to choose from, depending on what fits your needs best: 1. Override the
tts_node
Method:
• You can define a custom
tts_node
method in your agent class to gently preprocess text or tweak the audio just the way you like. • If you want to build on the existing setup, simply use
Agent.default.tts_node()
to call the default TTS pipeline, adding your own modifications smoothly. 2. Create a Fully Custom TTS Engine: • If you prefer more control, you can create a custom TTS class by inheriting from
tts.TTS
. • Then, implement methods like
synthesize()
or
stream()
to handle audio synthesis exactly how you want it. • Don’t forget to manage the audio output with
AudioEmitter
and integrate it nicely into your agent. If you’d like, I’m here to walk you through either approach in more detail—just let me know how I can help! Sources: Pipeline nodes and hooks | LiveKit docs | docs/index.yaml | Text-to-speech (TTS) models | LiveKit Docs | livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/tts.py
a
here's the code from Murf AI TTS Streaming Docs:
Copy code
import pyaudio
from murf import Murf, MurfRegion

client = Murf(
    api_key="YOUR_API_KEY", # Not required if you have set the MURF_API_KEY environment variable
    region=MurfRegion.GLOBAL
)

# For lower latency, specify a region closer to your users
# client = Murf(region=MurfRegion.IN)  # Example: India region

# Audio format settings (must match your API output)
SAMPLE_RATE = 24000  
CHANNELS = 1
FORMAT = pyaudio.paInt16

def play_streaming_audio():
    # Get the streaming audio generator
    audio_stream = client.text_to_speech.stream(
        text="Hi, How are you doing today?",
        voice_id="Matthew",
        model="FALCON",
        multi_native_locale="en-US",
        sample_rate=SAMPLE_RATE,
        format="PCM"
    )

    # Setup audio stream for playback
    pa = pyaudio.PyAudio()
    stream = pa.open(format=FORMAT, channels=CHANNELS, rate=SAMPLE_RATE, output=True)

    try:
        print("Starting audio playback...")
        for chunk in audio_stream:
            if chunk:  # Check if chunk has data
                stream.write(chunk)
    except Exception as e:
        print(f"Error during streaming: {e}")
    finally:
        stream.stop_stream()
        stream.close()
        pa.terminate()
        print("Audio streaming and playback complete!")

if __name__ == "__main__":
    play_streaming_audio()
and Here's my agent class:
Copy code
"""
PipelineAssistant class for Enhanced Dynamic Assistant with Custom Pronunciation for stt/llm/tts pipeline
"""

# Standard library imports
import asyncio
import os
import re
import logging
import aiohttp
from typing import AsyncIterable

# LiveKit imports
from livekit import api, rtc
from livekit.agents import (
    Agent,
    function_tool,
    RunContext,
    ChatContext,
    ChatMessage,
    ModelSettings,
)
from livekit.protocol.sip import TransferSIPParticipantRequest

# Import our modular services
from services.rag_service import RAGLookup, extract_text_from_message
from services.utils import get_participant_from_context_file, participant_mapping
from services.pronunciation_service import PronunciationService

from core.logger import get_logger

# Configure logger
logger = logging.getLogger("voice-agent")


# ───────────────────────────────────────────────────────
# ASR/LLM/TTS Pipeline Assistant with Dynamic Call Transfer and Enhanced RAG
# Usage: This Agent subclass is used when user triggers a voice pipeline with custom prompt, STT/LLM/TTS.
# ───────────────────────────────────────────────────────
class PipelineAssistant(Agent):
    """An Agent subclass that lets us plug in prompt, STT/LLM/TTS on demand with enhanced RAG, call transfer and custom pronunciation."""

    def __init__(self, instructions: str, welcome_msg: str, room_name: str, is_outbound: bool = False, agent_phone: str = "", flow: str = ""):
        super().__init__(
            instructions=instructions,
        )
        self._welcome_msg = (welcome_msg or "Hello?").strip()
        self._is_outbound = is_outbound
        self.room_name = room_name
        self.agent_phone = agent_phone
        self.flow = flow
        # Use the pronunciation service
        self.pronunciation_service = PronunciationService()
        self.user_spoke = asyncio.Event()
        self.logger = get_logger("voice_pipeline_agent")

    async def tts_node(
        self,
        text: AsyncIterable[str],
        model_settings: ModelSettings
    ) -> AsyncIterable[rtc.AudioFrame]:
        """Custom TTS node with pronunciation adjustments from frontend."""
        
        try:
            # Process with modified text through the pronunciation service
            adjusted_text = self.pronunciation_service.apply_pronunciations(text)
            async for frame in super().tts_node(adjusted_text, model_settings):
                yield frame
        except Exception:
            async for frame in super().tts_node(text, model_settings):
                yield frame
Now provide me example code to integrate Murf AI TTS with my voice_pipeline agent
t
I'm glad you're interested in integrating Murf AI TTS with your
PipelineAssistant
! To help you get started, you can create a custom TTS class that fits LiveKit's
tts.TTS
interface. Here's a friendly example implementation for you:
Copy code
from livekit import agents, rtc
from livekit.agents import tts
import aiohttp

class MurfTTS(tts.TTS):
    def __init__(self, api_key, voice_id="Matthew", sample_rate=24000):
        super().__init__(
            capabilities=tts.TTSCapabilities(streaming=True),
            sample_rate=sample_rate,
            num_channels=1,
        )
        self.api_key = api_key
        self.voice_id = voice_id
        self.base_url = "https://api.murf.ai/v1/synthesis"

    async def synthesize(self, text, conn_options):
        return MurfChunkedStream(self, text, conn_options)

class MurfChunkedStream(tts.ChunkedStream):
    async def _run(self, output_emitter):
        headers = {"Authorization": f"Bearer {self._tts.api_key}"}
        data = {
            "text": self._input_text,
            "voice_id": self._tts.voice_id,
            "sample_rate": self._tts.sample_rate,
        }

        async with aiohttp.ClientSession() as session:
            async with session.post(self._tts.base_url, headers=headers, json=data) as resp:
                resp.raise_for_status()
                output_emitter.initialize(
                    request_id="murf_request",
                    sample_rate=self._tts.sample_rate,
                    num_channels=1,
                    mime_type="audio/pcm",
                )
                async for chunk in resp.content.iter_any():
                    output_emitter.push(chunk)
                output_emitter.flush()
When you're ready to use this with your
PipelineAssistant
, you can simply swap in the TTS instance like this:
Copy code
agent = PipelineAssistant(
    instructions="Your instructions",
    welcome_msg="Hello!",
    room_name="example_room",
    tts=MurfTTS(api_key="YOUR_API_KEY", voice_id="Matthew")
)
This setup will stream audio directly from Murf AI and smoothly integrate it into your LiveKit pipeline. If you have any questions or need a hand with anything else, please don’t hesitate to ask — I’m here to help! Sources: Neuphonic TTS plugin guide | LiveKit Docs | .cursor/rules/agent-core.mdc | examples/other/kokoro_tts.py | Rime TTS plugin guide | LiveKit Docs | Hume TTS plugin guide | LiveKit Docs