AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Integrating Murf Falcon API for Ultra-Low-Latency Voice Agents and Streaming TTS

劉書磊 · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

In conversational AI and interactive voice systems (IVR), the difference between a natural dialogue and an awkward human-machine exchange comes down to milliseconds. When developers wire standard batch text-to-speech (TTS) interfaces into real-time voice bots, the user experience invariably breaks down. Batch synthesis forces the orchestrator to wait for the Large Language Model (LLM) to finish an entire sentence or paragraph, upload or stream it to a synthesis endpoint, wait for full audio compilation, and then buffer the resulting file. The consequence is a 1,500ms to 4,000ms latency pause (Time-to-First-Audio, or TTFA) that disrupts conversational pacing and triggers mutual interruptions.

To eliminate this bottleneck, Murf AI introduced Falcon 2.1 alongside native streaming architectures. Falcon 2.1 delivers a core model latency of approximately 55 milliseconds and an end-to-end Time-to-First-Audio under 100 to 130 milliseconds. At 365Finds, our research and benchmarking conclude that developers building production-grade voice agents must abandon legacy REST generation endpoints entirely. Integrating Murf AI's Falcon API over persistent WebSockets—configured with predictive chunking, raw PCM streaming, and scoped context IDs—is the gold standard for achieving fluid, human-like voice interactivity.

This guide provides technical architectures, API specifications, WebSocket and HTTP stream protocols, pronunciation rules, and production deployment strategies for building high-concurrency, ultra-low-latency voice pipelines with Murf AI.


1. Architectural Reality: Batch Synthesis vs. Streaming TTS

Human conversational turn-taking occurs within an average cognitive window of 250 to 500 milliseconds. If an automated customer support bot or voice assistant exceeds this threshold, callers assume the agent has disconnected or failed to understand, leading them to speak again just as the agent begins its delayed response.

The following breakdown illustrates where latency accumulates in conversational voice pipelines:

Pipeline StageLegacy Batch TTS ArchitectureMurf Falcon 2.1 Streaming Architecture
LLM Text IngestionMust await full sentence completion (500–1,200 ms)Streams tokens incrementally to TTS socket (0 ms wait)
Network HandshakeRepeated TCP/TLS connection per turn (30–80 ms)Persistent WebSocket connection (0 ms per turn)
Model Synthesis Latency400–1,500 ms (processes full audio chunk)~55 ms core model synthesis latency
Audio Delivery MechanismMonolithic audio file download (MP3/WAV)Chunked streaming bytes / base64 PCM frames
Time-to-First-Audio (TTFA)1,500 ms – 3,500+ ms (Unusable for live dialogue)~100 ms – 130 ms (Natural human turn-taking)
Barge-In HandlingServer audio completes synthesis; difficult cancellationNative clear frames discard queued audio instantly

365Finds Assessment

365Finds strongly advises engineering teams to classify batch TTS endpoints (such as Murf Gen 2 POST /v1/speech/generate) strictly as offline studio tools for video narration, podcast editing, or static assets. Attempting to wrap batch endpoints in client-side threading or sentence buffers for live conversational agents is an anti-pattern. Real-time turn-taking mandates streaming models capable of incremental token consumption.


2. Protocol Selection: WebSocket (stream-input) vs. HTTP Streaming (stream)

Murf AI exposes Falcon 2.1 through two primary low-latency interfaces:

  1. Bidirectional WebSocket API: wss://global.api.murf.ai/v1/speech/stream-input
  2. HTTP Chunked Streaming API: https://global.api.murf.ai/v1/speech/stream

While both endpoints utilize the Falcon 2.1 model, their architectural fit differs significantly depending on the application context.

Protocol Comparison

DimensionWebSocket (/stream-input)HTTP Chunked (/stream)
Communication PatternFull-duplex bidirectional stream over persistent TCPUnidirectional HTTP/1.1 or HTTP/2 chunked transfer
Connection OverheadSingle TLS/TCP handshake for entire session/callHandshake required per request (unless connection pooled)
Input DeliveryIncremental token-by-token or phrase-by-phrase pushingFull prompt sent upfront in the POST payload body
Barge-In / InterruptionInstant via {"clear": true} frameMust abruptly abort TCP socket on the client side
Word TimestampsSupported natively via interleaved JSON timestamp framesUnsupported
Recommended Use CaseReal-time conversational AI, voice bots, phone IVRServerless microservices, web reader widgets, single prompts

Audio Container Format: Why 365Finds Recommends Raw PCM

When establishing the WebSocket connection or calling the HTTP stream, developers can specify output audio codecs via the format parameter (PCM, WAV, MP3, FLAC, OGG, ALAW, ULAW).


3. WebSocket Integration: Handshake, Voice Config, and Context IDs

The Falcon 2.1 WebSocket protocol centers on Context IDs. A Context ID (context_id) serves as the stateful proxy for a single conversational turn between the caller and the voice agent. It synchronizes text input with corresponding audio frames, manages concurrency limits, and handles interruption cancellations.

Step 1: Connecting to the Gateway

The client establishes a secure WebSocket connection. Global applications should connect to wss://global.api.murf.ai, which dynamically geo-routes traffic to the nearest regional cluster.

Query parameters configured during the handshake:

wss://global.api.murf.ai/v1/speech/stream-input?api-key=YOUR_API_KEY&model=falcon-2.1&format=PCM&sample_rate=24000&channel_type=MONO

Step 2: Sending the Voice Configuration Frame

Before streaming text for a named context, you must send a voice_config frame keyed with that context_id. Settings applied to one context_id are isolated and do not automatically inherit from previous turns or unscoped configurations.

{
  "voice_config": {
    "voiceId": "Gordon",
    "locale": "en-US",
    "style": "Conversation",
    "rate": 0,
    "pitch": 0,
    "volumeOffset": 15
  },
  "context_id": "turn_001"
}

Step 3: Streaming Incremental Text Frames

Once the context is configured, stream LLM tokens or sentences into the socket:

{
  "context_id": "turn_001",
  "text": "Hello, thank you for contacting support. How can I help you today?",
  "predictive_chunking": "lenient",
  "add_word_timestamps": true,
  "end": true
}

4. Latency Optimization: Predictive Chunking and LLM Token Pipelining

A frequent engineering error when deploying real-time voice bots is inserting an intermediate sentence tokenizer (such as NLTK, spaCy, or LiveKit's default text aggregator) between the LLM and the TTS socket. Double-buffering forces the application to wait for the local tokenizer to see a terminal punctuation mark before sending text to Murf AI, which then performs its own linguistic chunking.

Predictive Chunking (predictive_chunking)

Falcon 2.1 includes native boundary prediction designed specifically for tokenized LLM output. Developers should feed LLM text tokens straight into the Murf AI WebSocket as they arrive and let Falcon determine phrasing.

SettingModeBehaviorBest Used For
predictive_chunkingstrict (Default)Waits for subsequent characters when encountering ambiguous periods (2 p.m., Dr., Inc.).Long-form narration, formal document reading where pauses must be avoided.
predictive_chunkinglenientGuesses sentence boundaries immediately and begins synthesis on the fly.Voice agents and interactive conversational bots where TTFA is paramount.

Buffer Threshold Tuning

If the LLM streams text with sparse punctuation, Falcon relies on two buffer fallback controls placed at the top level of the payload:

[!TIP] Setting both min_buffer_size: 0 and max_buffer_delay_in_ms: 0 achieves the lowest possible Time-to-First-Byte, but each emitted word fragment will be synthesized as an isolated prosodic unit, resulting in unnatural cadence. 365Finds recommends setting predictive_chunking: "lenient" and prompting your LLM with strict instructions to output standard punctuation early in responses.


5. Handling Interruptions and Barge-In

In fluid voice conversations, users routinely interrupt the agent before it finishes speaking. To support seamless barge-in:

  1. Detect User Speech: The client-side Voice Activity Detector (VAD) detects incoming user audio.
  2. Halt Local Audio Playback: Instantly mute the client output buffer.
  3. Dispatch a clear Frame: Send {"clear": true, "context_id": "current_turn"} to Murf AI. Falcon drops all pending text and queued audio generation for that context.
  4. Initialize Next Turn: Send a new voice_config and subsequent text payload keyed with a fresh context_id (e.g., turn_002).
sequenceDiagram
    autonumber
    actor User
    participant Client as Voice Agent Client
    participant Murf as Murf Falcon WebSocket
    
    User->>Client: "What are your business hours?"
    Client->>Murf: Send voice_config (context_id: turn_1)
    Client->>Murf: Stream text tokens (context_id: turn_1)
    Murf-->>Client: Streaming audio chunks (turn_1)
    Client-->>User: Playing audio: "We are open Monday through..."
    
    User->>Client: Interrupts: "Wait, what about Sunday?"
    Note over Client: VAD triggers Barge-In
    Client->>Client: Immediately halt audio playback
    Client->>Murf: Send {"clear": true, "context_id": "turn_1"}
    Note over Murf: Discards pending generation for turn_1
    Client->>Murf: Send voice_config (context_id: turn_2)
    Client->>Murf: Stream text: "On Sundays we are open 10 to 4." (turn_2)
    Murf-->>Client: Streaming audio chunks (turn_2)
    Client-->>User: Playing audio: "On Sundays we are open..."

[!WARNING] Never combine "clear": true and "text": "..." in the exact same JSON frame. Doing so causes Falcon to drop the text and emit a TEXT_IGNORED_WITH_CLEAR warning. Clearing and initiating a new turn must occur across separate WebSocket frames.

Word Timestamps for Conversation State

When "add_word_timestamps": true is enabled, Murf AI streams discrete JSON frames containing word-level start and end times:

{
  "context_id": "turn_001",
  "trace_id": "e94ab7c1-8d20-43b9-8e2b-7f289d0e1941",
  "timestamps": {
    "words": [
      {
        "word": "Hello",
        "start_s": 0.0,
        "end_s": 0.38,
        "start_frame": 0,
        "end_frame": 18
      },
      {
        "word": "there",
        "start_s": 0.40,
        "end_s": 0.72,
        "start_frame": 19,
        "end_frame": 35
      }
    ]
  }
}

When a user interrupts at time $T$, compare $T$ to start_s. Discard all timestamp records where start_s > T. This informs your conversation memory exactly which words the user heard, preventing the LLM from falsely assuming information was conveyed.


6. Precision Pronunciation: Inline IPA vs. Pronunciation Dictionary

Automated voice agents regularly mispronounce brand names, technical jargon, medical nomenclature, and customer surnames. Falcon 2.1 provides two distinct mechanisms to enforce phonetic precision:

Method 1: Inline International Phonetic Alphabet (IPA)

You can directly embed IPA notation into the stream text by enclosing the phonetic string in forward slashes wrapped in double quotes: "/IPA/".

Method 2: Structured Pronunciation Dictionary

For persistent enterprise vocabularies, pass a dictionary mapping words to their phonetic representation. On WebSockets, include pronunciation_dictionary inside the voice_config frame; on HTTP streaming, pass pronunciationDictionary at the top level.

{
  "voice_config": {
    "voiceId": "Gordon",
    "pronunciation_dictionary": {
      "Murf": {
        "type": "IPA",
        "pronunciation": "mɜːrf"
      },
      "TTS": {
        "type": "SAY_AS",
        "pronunciation": "text to speech"
      },
      "AES-256": {
        "type": "SAY_AS",
        "pronunciation": "A E S two fifty six"
      }
    }
  },
  "context_id": "turn_001"
}

365Finds Recommendation on Pronunciation Strategy

Do not instruct your LLM to generate inline IPA for common words or enterprise glossaries. Forcing an LLM to output phonemes increases output token generation overhead, adding 100ms to 300ms of LLM inference latency. Instead, declare static brand terms, acronyms, and product models in the pronunciation_dictionary within voice_config. Reserve inline IPA exclusively for dynamic customer names injected into prompts via your orchestration layer.


7. Python Implementation: Full Conversational Streaming Client

Below is a complete, production-ready Python client utilizing websockets and asyncio to establish an ultra-low-latency Falcon 2.1 pipeline, stream simulated LLM tokens, handle context lifecycle, and manage interruption barge-in.

import asyncio
import json
import base64
import os
import websockets

MURF_API_KEY = os.getenv("MURF_API_KEY", "your_murf_api_key")
# Global auto-routing endpoint
WS_URL = "wss://global.api.murf.ai/v1/speech/stream-input"

async def voice_agent_turn(ws, context_id: str, text_stream, voice_id: str = "Gordon"):
    """
    Executes a single conversational agent turn with Murf Falcon 2.1.
    """
    # 1. Initialize the Voice Configuration for this Turn
    voice_config_payload = {
        "voice_config": {
            "voiceId": voice_id,
            "locale": "en-US",
            "style": "Conversation",
            "rate": 0,
            "pitch": 0,
            "volumeOffset": 10,
            "pronunciation_dictionary": {
                "Murf": {"type": "IPA", "pronunciation": "mɜːrf"},
                "IVR": {"type": "SAY_AS", "pronunciation": "interactive voice response"}
            }
        },
        "context_id": context_id
    }
    await ws.send(json.dumps(voice_config_payload))
    print(f"[{context_id}] Voice config dispatched.")

    # 2. Concurrently stream tokens and ingest synthesized audio
    async def stream_tokens():
        async for token in text_stream:
            payload = {
                "context_id": context_id,
                "text": token,
                "predictive_chunking": "lenient",
                "add_word_timestamps": True,
                "end": False
            }
            await ws.send(json.dumps(payload))
            await asyncio.sleep(0.02)  # Simulate 20ms LLM token generation interval

        # Close the turn
        await ws.send(json.dumps({"context_id": context_id, "text": "", "end": True}))
        print(f"[{context_id}] End-of-turn token sent.")

    async def receive_audio():
        first_byte_received = False
        while True:
            raw_msg = await ws.recv()
            data = json.loads(raw_msg)

            # Audio Frame
            if "audio" in data:
                audio_bytes = base64.b64decode(data["audio"])
                if not first_byte_received:
                    print(f"[{context_id}] >>> FIRST AUDIO CHUNK RECEIVED (TTFA achieved) <<<")
                    first_byte_received = True
                # Pipe raw PCM bytes directly to playback / WebRTC audio sink
                # audio_sink.write(audio_bytes)

            # Word Timestamps Frame
            if "timestamps" in data:
                words = data["timestamps"].get("words", [])
                for w in words:
                    print(f"[{context_id}] Word: '{w['word']}' ({w['start_s']}s - {w['end_s']}s)")

            # Final Frame (Turn Complete)
            if data.get("final"):
                concurrency = data.get("concurrency", {})
                print(f"[{context_id}] Turn finalized. Region: {concurrency.get('region')}, "
                      f"Active: {concurrency.get('used')}/{concurrency.get('limit')}")
                break

            if data.get("error"):
                print(f"[{context_id}] Error {data.get('error_code')}: {data.get('error')}")
                if data.get("fatal"):
                    break

    await asyncio.gather(stream_tokens(), receive_audio())

async def interrupt_turn(ws, active_context_id: str):
    """
    Sends an immediate cancellation frame to stop audio synthesis.
    """
    clear_payload = {
        "context_id": active_context_id,
        "clear": True
    }
    await ws.send(json.dumps(clear_payload))
    print(f"[{active_context_id}] Cancelled via barge-in.")

async def main():
    # Connect with raw PCM format to avoid 44-byte WAV header handling
    connect_url = (
        f"{WS_URL}?api-key={MURF_API_KEY}"
        f"&model=falcon-2.1"
        f"&sample_rate=24000"
        f"&channel_type=MONO"
        f"&format=PCM"
    )

    async with websockets.connect(connect_url) as ws:
        # Simulate LLM Token Generator
        async def mock_llm_stream():
            tokens = [
                "Welcome ", "to ", "Murf ", "AI. ",
                "Our ", "Falcon ", "engine ", "enables ",
                "sub-second ", "streaming ", "voice ", "agents."
            ]
            for t in tokens:
                yield t

        # Execute Turn 1
        await voice_agent_turn(ws, "turn_001", mock_llm_stream())

if __name__ == "__main__":
    asyncio.run(main())

8. Enterprise Concurrency, Data Residency, and Edge Deployment

Deploying real-time voice infrastructure at scale requires strict adherence to network routing and regional concurrency caps:

Regional Endpoints and Data Residency

Murf AI operates 11 isolated regional endpoints. While the Global Router (global.api.murf.ai) minimizes latency through Anycast-style DNS, enterprise compliance policies (e.g., GDPR, HIPAA) may require pinning connections to a specific jurisdiction:

RegionWebSocket EndpointDefault Concurrency
Global Routerwss://global.api.murf.ai/v1/speech/stream-inputRouted Region Cap
US-East (N. Virginia)wss://us-east.api.murf.ai/v1/speech/stream-input5
US-West (Oregon)wss://us-west.api.murf.ai/v1/speech/stream-input2
EU Central (Frankfurt)wss://eu-central.api.murf.ai/v1/speech/stream-input2
UK (London)wss://uk.api.murf.ai/v1/speech/stream-input2
India (Mumbai)wss://in.api.murf.ai/v1/speech/stream-input2
Japan (Tokyo)wss://jp.api.murf.ai/v1/speech/stream-input2
Australia (Sydney)wss://au.api.murf.ai/v1/speech/stream-input2
South Korea (Seoul)wss://kr.api.murf.ai/v1/speech/stream-input2
UAE (Dubai)wss://me.api.murf.ai/v1/speech/stream-input2
Canada (Central)wss://ca.api.murf.ai/v1/speech/stream-input2
South America (São Paulo)wss://sa-east.api.murf.ai/v1/speech/stream-input2

Managing Concurrency Limits

Standard developer plans throttle accounts that exceed concurrent active contexts (returning error ACTIVE_CONTEXT_LIMIT_EXCEEDED and closing sockets with code 4029).


9. 365Finds Strategic Evaluation & Integration Checklist

For engineering leaders evaluating Murf AI's Falcon API against competitors like ElevenLabs, Deepgram Aura, or Cartesia:


References