AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How to Integrate the Murf API and Falcon Model for Real-Time Low-Latency Voice Applications

Amanda Nagy · 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

For backend full-stack engineers, conversational AI architects, and VoIP telephony developers, the primary bottleneck in building interactive voice agents is首包音频延迟 (Time to First Audio, or TTFA). Traditional text-to-speech (TTS) REST endpoints generate an entire audio file before responding, imposing latency penalties of 500 ms to over 2,000 ms. In conversational systems—such as automated customer support, AI receptionists, interactive gaming NPCs, and outbound debt collections—delays exceeding 300 ms disrupt natural conversational rhythm, causing awkward human-robot cross-talk and user frustration.

Murf AI addresses this performance threshold with its native real-time model, Falcon (specifically the production iteration Falcon 2.1), paired with a bidirectional streaming WebSocket architecture. Falcon delivers a model synthesis latency of roughly 55 ms and a production median TTFA under 100 ms (consistently benchmarking at ~95 ms in production cloud environments), priced economically at approximately $0.01 per minute ($0.01 per 1,000 characters).

At 365Finds, our engineering recommendation is definitive: Do not use HTTP batch synthesis or framework-level text aggregators for real-time voice agents. Achieving sub-100 ms responsiveness requires an end-to-end streaming pipeline: establish a persistent WebSocket session via Murf AI's global or regional edge routers, stream raw Large Language Model (LLM) token fragments directly into Falcon, configure predictive_chunking: "lenient", and consume uncompressed 16-bit linear PCM audio.

flowchart LR
    Caller["User / WebRTC Client"] -->|Voice Audio| STT["Speech-to-Text Engine"]
    STT -->|Text Tokens| LLM["Conversational LLM"]
    LLM -->|Token Stream| Server["Backend Orchestrator"]
    Server -->|WebSocket wss://...| Murf["Murf AI Falcon 2.1 Engine"]
    Murf -->|Sub-100ms Audio Chunks| Server
    Server -->|RTP / WebRTC Stream| Caller

1. Architectural Architecture: WebSocket Streaming vs. REST Authentication

A resilient enterprise voice pipeline separates credential control from high-throughput streaming transport. Murf AI implements this separation through dual endpoints:

  1. REST Authentication Endpoint (https://api.murf.ai/v1/auth/token): Used on your secure application server to issue short-lived, ephemeral authentication tokens (token, expiryInEpochMillis). This prevents exposing your permanent api-key in client-side WebRTC clients, browser front-ends, or mobile edge devices.
  2. WebSocket Streaming Endpoint (wss://global.api.murf.ai/v1/speech/stream-input): A persistent, full-duplex connection over which voice configurations, partial text deltas, interruption signals, and synthesized audio chunks travel with minimal transport overhead.

Endpoint Matrix and Geographic Routing

DNS resolution and TLS handshakes add 30 ms to 80 ms of latency when requests open new connections. You should establish one persistent WebSocket connection per call and route traffic through Murf AI's nearest regional gateway:

Target RegionRegional EndpointPrimary Use Case
Global Routerwss://global.api.murf.ai/v1/speech/stream-inputDynamic geo-routing to the nearest available server
US East (N. Virginia)wss://us-east.api.murf.ai/v1/speech/stream-inputDefault high-concurrency hub (up to 5 default streams)
US West (Oregon)wss://us-west.api.murf.ai/v1/speech/stream-inputWest Coast US and Pacific failover
India (Mumbai)wss://in.api.murf.ai/v1/speech/stream-inputIndian subcontinent and Indic code-mixing workloads
EU Central (Frankfurt)wss://eu-central.api.murf.ai/v1/speech/stream-inputGDPR-compliant European deployments
United Kingdom (London)wss://uk.api.murf.ai/v1/speech/stream-inputUK regulatory and local voice agents
APAC (Tokyo / Seoul / Sydney)wss://jp.api.murf.ai/..., wss://kr.api.murf.ai/..., wss://au.api.murf.ai/...East Asian and Australian latency optimization

[!IMPORTANT] The legacy hostname api.murf.ai maps strictly to US East without geo-routing. In production, always use global.api.murf.ai or explicit regional prefixes like in.api.murf.ai or eu-central.api.murf.ai to guarantee data residency and minimize Round-Trip Time (RTT).


2. Managing Turn Lifecycle and Concurrency with Context IDs

Murf AI models conversational turn-taking using a concept called Context ID (context_id). Each dialog turn between the caller and the voice agent is assigned an independent context. This construct allows your application to reuse a single open WebSocket connection for the entire phone call while multiplexing separate LLM responses.

The Handshake and Turn Execution Sequence

Every turn requires a strict two-stage payload sequence:

  1. Voice Configuration Frame: Sent first to initialize voice attributes, pitch, rate, and style for that specific context_id.
  2. Text Input Frames: Subsequent JSON frames delivering text chunks as the LLM yields tokens.
  3. Turn Finalization: Marking "end": true on the final text delta to trigger audio completion and release server concurrency slots.
sequenceDiagram
    autonumber
    actor Caller
    participant App as Voice Agent Server
    participant Murf as Murf AI Falcon (WebSocket)

    Note over App,Murf: Connection established (model=falcon-2.1)
    Caller->>App: "Can I reschedule my appointment?"
    App->>Murf: Send voice_config (context_id: "turn_101", voiceId: "Gordon")
    App->>Murf: Send text chunk 1 ("Sure, ")
    App->>Murf: Send text chunk 2 ("what time works best?") (end: true)
    Murf-->>App: Stream audio chunks (Base64 PCM)
    App-->>Caller: Progressive Playback (<100ms TTFA)
    Murf-->>App: final frame (concurrency usage, slot freed)

Critical Voice Configuration Rules


3. Audio Chunking, Codecs, and the 44-Byte WAV Header Trap

A subtle issue in voice streaming integration centers on audio framing and container headers. Murf AI supports both format=WAV and format=PCM.

The 44-Byte WAV Header Behavior

When requesting format=WAV, the Falcon engine does not know the final audio duration when streaming begins. Consequently, the very first audio chunk of each context prepends a standard 44-byte RIFF WAV header containing placeholder sizes (0xFFFFFFFF, representing unknown stream length). Subsequent audio chunks in that turn contain raw audio bytes without headers.


4. Latency Engineering: Achieving True Sub-100ms TTFA

To push TTFA below the 100 ms threshold in production, technical teams must optimize four specific layers:

1. Enable Lenient Predictive Chunking

Falcon evaluates sentence boundaries using terminal punctuation (., ?, !, and Devanagari ।). In standard conversational speech, abbreviations (such as Dr., e.g., or 2 p.m.) introduce ambiguity: does the period represent an abbreviation or the end of the sentence?

{
  "context_id": "turn_101",
  "text": "Your flight departs at 6 a.m. tomorrow.",
  "predictive_chunking": "lenient"
}

[!WARNING] Top-level parameters like predictive_chunking, min_buffer_size, max_buffer_delay_in_ms, and add_word_timestamps must sit at the top level of the JSON frame alongside text. Placing them inside voice_config causes Falcon to silently ignore them.

2. Disable Double Tokenization in Agent Frameworks

If you use voice frameworks like LiveKit Agents or Pipecat, disable the framework's internal sentence tokenizer (such as nltk, spacy, or regex text accumulators).

When a framework buffers LLM tokens into full sentences before sending them to Murf AI, you incur two consecutive buffering delays. Because Murf AI's Falcon engine executes its own internal sentence boundary detection, streaming raw LLM tokens directly over the WebSocket eliminates duplicate buffering and shaves 100 ms to 250 ms off conversational turn latency.

3. Buffer Settings for Raw LLM Output

If your upstream LLM streams text without punctuation, Falcon relies on two safety buffers:

For voice agents, setting min_buffer_size: 40 and max_buffer_delay_in_ms: 200 ensures that slow LLM token generation does not starve the audio pipeline.


5. Handling Conversational Barge-In and Word Timestamps

Natural conversations require callers to be able to interrupt the AI agent mid-sentence. Implementing barge-in over WebSockets requires coordinated cancellation and audio clipping.

The Interruption Cancellation Protocol

When Voice Activity Detection (VAD) detects caller speech while the agent is speaking:

  1. Mute Client Audio Immediately: Stop audio playback in your local speaker buffer.
  2. Issue Clear Frame: Send a dedicated frame with "clear": true and the active context_id. This drops queued text and halts unrendered audio generation on Murf AI's servers.
  3. Start New Context: Immediately initiate the subsequent turn under a fresh context ID.
{
  "context_id": "turn_101",
  "clear": true
}

[!CAUTION] Never combine "clear": true and new "text" in the same JSON frame. Doing so causes Murf AI to discard the text and return a TEXT_IGNORED_WITH_CLEAR warning. Clear the old turn and send the new turn in two separate WebSocket frames.

Word Timestamps for Conversational State Tracking

To know exactly which words the caller heard before interrupting, set "add_word_timestamps": true on the WebSocket connection. Murf AI streams standalone JSON metadata frames interleaving audio:

{
  "context_id": "turn_101",
  "trace_id": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d",
  "timestamps": {
    "words": [
      {
        "word": "reschedule",
        "start_s": 0.32,
        "end_s": 0.78,
        "start_frame": 7680,
        "end_frame": 18720
      }
    ]
  }
}

By comparing the caller's barge-in timestamp against end_s, your backend state machine knows whether the user heard critical information (such as an appointment time or payment amount) before interrupting, avoiding repetitive re-prompting.


6. Multilingual Code-Mixing and Pronunciation Control

Global enterprises often operate in bilingual markets where speakers blend languages in everyday speech—such as Hinglish (Hindi + English), Spanglish (Spanish + English), or Taglish.

Native Multi-Language Fluidity

Falcon voices are architected as multinative. A single voice model (such as Gordon or Amara) dynamically synthesizes multiple languages within the same sentence without requiring language tags or voice switching.

"आपका loan approval complete हो गया है, please verify your email address."

The Script Selection Rule

The script used for non-Latin text has a direct impact on latency:

Precise Phonetic Tuning via Inline IPA and Dictionaries

For specialized terms, medical drugs, and brand names, standard text normalization can mispronounce words. Murf AI offers two pronunciation solutions:

  1. Inline IPA Annotation: Enclose International Phonetic Alphabet (IPA) strings in quotation marks and forward slashes directly within your text stream:
    Welcome to "/mɜːrf/" voice systems.
    
  2. Pronunciation Dictionary: Pass a pronunciation_dictionary object inside your initial voice_config payload:
    "pronunciation_dictionary": {
      "365Finds": {
        "type": "IPA",
        "pronunciation": "θriː sɪks faɪv faɪndz"
      }
    }
    

Real-Time Volume Offsets for Telephony

Default studio voice levels can sound muffled or faint across narrowband PSTN telephone lines or noisy vehicle environments. Rather than running a CPU-intensive digital gain filter on your application server, send volumeOffset (ranging from -50 to 50) inside voice_config.

Setting volumeOffset: 15 to 25 boosts vocal presence across telephone networks directly inside the streaming synthesis engine with zero added latency.


7. Production Code Walkthrough: Python Async WebSocket Pipeline

The following Python implementation demonstrates an asynchronous, enterprise-grade streaming pipeline. It manages connection setup, turn isolation, predictive chunking, base64 audio decoding, and graceful error handling:

import asyncio
import base64
import json
import os
import sys
import websockets

MURF_API_KEY = os.getenv("MURF_API_KEY", "your_api_key_here")
# Global geo-routing WebSocket gateway
WS_URL = "wss://global.api.murf.ai/v1/speech/stream-input"

async def stream_voice_agent_turn(
    ws: websockets.WebSocketClientProtocol,
    turn_id: str,
    voice_id: str,
    text_generator,
):
    """
    Executes a single conversational agent turn with sub-100ms streaming audio.
    """
    # 1. Initialize Voice Configuration for this Context ID
    init_config = {
        "voice_config": {
            "voiceId": voice_id,
            "locale": "en-US",
            "style": "Conversation",
            "rate": 0,
            "pitch": 0,
            "volumeOffset": 15,  # Optimized for VoIP telephony loudness
        },
        "context_id": turn_id,
    }
    await ws.send(json.dumps(init_config))

    # 2. Stream LLM Text Tokens as they arrive
    async def send_text_stream():
        async for token_chunk, is_last in text_generator:
            payload = {
                "text": token_chunk,
                "context_id": turn_id,
                "predictive_chunking": "lenient",  # Minimize TTFA
                "min_buffer_size": 30,
                "max_buffer_delay_in_ms": 200,
            }
            if is_last:
                payload["end"] = True  # Closes context & frees concurrency slot
            await ws.send(json.dumps(payload))

    # 3. Concurrently receive audio chunks from Falcon
    async def receive_audio_stream():
        total_audio_bytes = 0
        first_byte_received = False

        while True:
            raw_msg = await ws.recv()
            msg = json.loads(raw_msg)

            # Check for error frames
            if msg.get("error"):
                print(f"[Murf Error] Code {msg.get('error_code')}: {msg.get('error')}", file=sys.stderr)
                if msg.get("fatal"):
                    break

            # Process synthesized audio chunks
            if "audio" in msg and msg.get("context_id") == turn_id:
                audio_bytes = base64.b64decode(msg["audio"])
                total_audio_bytes += len(audio_bytes)

                if not first_byte_received:
                    first_byte_received = True
                    print(f"[{turn_id}] First audio byte arrived! Outputting stream...")

                # Write directly to playback stream / WebRTC audio sink
                # (e.g., jitter_buffer.push(audio_bytes))

            # Turn completed
            if msg.get("final") and msg.get("context_id") == turn_id:
                usage = msg.get("concurrency", {})
                print(f"[{turn_id}] Completed. Server Region: {usage.get('region')}, "
                      f"Concurrency: {usage.get('used')}/{usage.get('limit')}")
                break

    await asyncio.gather(send_text_stream(), receive_audio_stream())

async def mock_llm_token_generator():
    """Simulates an LLM token generator yielding partial text."""
    tokens = [
        ("Hello, ", False),
        ("thank you for calling support. ", False),
        ("I can help you reschedule your flight to Paris ", False),
        ("for tomorrow morning.", True),
    ]
    for token, is_last in tokens:
        await asyncio.sleep(0.04)  # Simulate 40ms token generation delay
        yield token, is_last

async def main():
    # Connect using raw PCM format to avoid container header stripping
    query_params = (
        f"?api-key={MURF_API_KEY}"
        "&model=falcon-2.1"
        "&sample_rate=24000"
        "&channel_type=MONO"
        "&format=PCM"
    )
    uri = WS_URL + query_params

    print("Connecting to Murf Falcon WebSocket gateway...")
    async with websockets.connect(uri) as ws:
        print("Connected successfully. Streaming Turn 1...")
        await stream_voice_agent_turn(
            ws=ws,
            turn_id="call-turn-001",
            voice_id="Gordon",
            text_generator=mock_llm_token_generator(),
        )

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

8. Architectural Verdict & Production Checklist

Integrating Murf AI's Falcon model transforms voice agent responsiveness from sluggish batch interaction into instantaneous, human-like dialogue. When designing enterprise production pipelines, evaluate your architecture against the following engineering checklist:

Architecture LayerSub-Optimal PracticeRecommended 365Finds Standard
TransportREST HTTP POST pollingPersistent WebSocket connection with keep-alive pooling
Audio Formatformat=WAV (requires 44-byte sentinel header stripping)format=PCM (headerless 16-bit linear PCM, 24 kHz or 8 kHz)
Sentence ChunkingFramework-level sentence tokenizers (e.g., LangChain / LiveKit)Disable external tokenizers; stream directly to Falcon with predictive_chunking: "lenient"
Multilingual InputRomanized Indic / transliterated Latin charactersNative script (Devanagari for Hindi, Tamil for Tamil)
InterruptionServer-side connection terminationTargeted {"clear": true} sent under the specific context_id
Gain StagingClient-side CPU digital post-processingIn-engine volumeOffset (10 to 25 for PSTN telephony)

By aligning your software stack with Falcon's streaming design—relying on persistent regional sockets, raw PCM streaming, and context-aware turn management—technical teams can deliver robust, sub-100ms conversational AI voice applications at enterprise scale.

References