OpenAI Realtime API on a Phone Call: Full Walkthrough

This walkthrough covers how to connect the OpenAI Realtime API to a live PSTN phone call using WebSocket transport and a telephony bridge. It explains the audio format mismatch between...
openai realtime api phone call pcm 24khz g711 8khz codec feature
In this article

AI Summary: This article is a technical walkthrough for backend and API integration engineers who want to put the OpenAI Realtime API on a live phone call in 2026. The core constraint is an audio format mismatch: the OpenAI Realtime API expects PCM audio at 24 kHz, while narrowband PSTN carriers deliver G.711 at 8 kHz, so a resampling step is mandatory on every phone-call path. Engineers must supply their own telephony transport, number provisioning, codec bridging, and call control. Teler provides the WebSocket media streaming layer and carrier connectivity that bridges the gap between the PSTN leg and the model session.

Scope: This walkthrough covers streaming audio between the OpenAI Realtime API and a live PSTN call over Teler’s WebSocket transport, verified against the API shape documented in September 2026. It does not cover SIP trunk provisioning in depth or WebRTC browser paths.

Quick Answer: To put the OpenAI Realtime API on a phone call in 2026, open a WebSocket to wss://api.openai.com/v1/realtime, resample the carrier’s 8 kHz G.711 audio to 24 kHz PCM before sending it to the model, and inject the model’s 24 kHz PCM output back into the call leg after downsampling. A telephony bridge such as Teler handles carrier connectivity and raw media streaming so your server works at the application layer.

Connecting the OpenAI Realtime API to a phone call requires bridging two incompatible audio worlds: the 8 kHz G.711 stream that PSTN carriers deliver and the 24 kHz PCM stream the model expects. Most teams underestimate this gap until they hear garbled audio on their first live call.

What is the OpenAI Realtime API?

The OpenAI Realtime API is a stateful, event-based speech-to-speech API that communicates over WebSocket or WebRTC and lets a developer build voice agents that interpret audio, reason, call tools, and respond in synthesized speech within a single session. It occupies the model layer: it handles turn detection, audio transcription, LLM inference, and text-to-speech output, but it does not provide phone numbers, carrier access, or PSTN connectivity. The API is not a CPaaS (Communications Platform as a Service) and does not provision DIDs (Direct Inward Dialing numbers) or SIP trunks. A developer who wants to put it on a real phone call must supply their own telephony transport, number provisioning, codec bridging, jitter buffering, and call control logic.

openai realtime api phone call audio format metrics frame size grid

Why is bridging the OpenAI Realtime API to a phone call hard?

The fundamental problem is a format mismatch at every layer of the stack. Carrier audio arrives as G.711 (PCM mu-law or A-law) at 8 kHz. The OpenAI Realtime API expects audio/pcm at 24 kHz, mono, 16-bit little-endian, or G.711 at 8 kHz via audio/pcmu or audio/pcma. If you send 8 kHz G.711 directly, the model accepts it, but the output comes back as 24 kHz PCM, which you must downsample before injecting into the RTP stream back to the caller.

Beyond codec conversion, a phone call introduces jitter: RTP packets (defined in RFC 3550) arrive out of order and with variable delay. A jitter buffer smooths this before the audio reaches the model, but it adds latency. The OpenAI Realtime API’s documented session limit is 60 minutes with a 32,768-token context window, and the research from open.cx reports that sub-300ms first-token latency is achievable in US and EU regions under normal conditions. Latency climbs on longer sessions as context grows, so session rotation is a real operational concern.

VAD (Voice Activity Detection) adds another wrinkle. The API supports server_vad, semantic_vad, and a disabled mode that requires explicit input_audio_buffer.commit calls. On a phone call, the caller’s silence is not always meaningful: hold music, background noise, and DTMF tones all arrive in the audio stream. Choosing the wrong VAD mode causes the model to respond to noise or miss real speech.

What does the audio path look like end to end?

The path from caller to model and back involves four distinct hops, each with its own format, transport, and owner. The table below maps them out.

HopFormatSample rateTransportOwner
Carrier to telephony bridgeG.711 mu-law or A-law (audio/pcmu, audio/pcma)8 kHzSIP/RTP (RFC 3261)Carrier + telephony layer
Telephony bridge to your server16-bit PCM8 kHzWebSocketTeler
Your server to OpenAI Realtime APIaudio/pcm (24 kHz) or audio/pcmu / audio/pcma (8 kHz)24 kHz or 8 kHzWebSocket to wss://api.openai.com/v1/realtimeYour server
OpenAI Realtime API output to calleraudio/pcm24 kHz (must downsample)WebSocket, then RTPYour server + telephony layer

Teler streams call audio to your server in chunks of 20 to 2000 milliseconds (multiples of 20, default 400 ms) as 16-bit PCM at 8 kHz. OpenAI’s audio/pcm format runs at 24 kHz, so you upsample each inbound chunk from 8 kHz to 24 kHz before forwarding it to the model. The model’s output arrives as 24 kHz PCM, which you downsample to 8 kHz before sending it back through Teler

What do you need before step one?

  • An OpenAI API key with Realtime API access enabled on your account
  • A Teler account with a provisioned phone number (available in 50+ countries via API) and a WebSocket media streaming endpoint configured
  • A server with a public WebSocket endpoint reachable by Teler (ngrok works for local development)
  • Node.js 18+ or Python 3.10+ with an async WebSocket library: ws for Node or websockets for Python (pip install websockets)
  • Uses NumPy and SciPy Signal (signal.decimate and signal.resample) in Python to perform high-quality audio downsampling and upsampling between 8 kHz, 16 kHz, and 24 kHz PCM audio formats for real-time communication between Teler and OpenAI.
  • Network reachability between your server and both wss://api.openai.com/v1/realtime and Teler’s WebSocket endpoint
  • Familiarity with the GA interface event shape; the beta interface using OpenAI-Beta: realtime=v1 was deprecated in May 2026 and connections using it now fail

How do you implement the OpenAI Realtime API on a phone call?

Step 1: Open the Realtime API WebSocket session

Open a WebSocket to the Realtime API endpoint and configure the session for 24 kHz PCM in both directions. The GA interface no longer accepts the OpenAI-Beta: realtime=v1 header, so omit it.

import asyncio
import json
import websockets

OPENAI_API_KEY = "sk-..."  # load from env, never hardcode
REALTIME_URL = "wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-12-17"

async def open_realtime_session():
    headers = {
        "Authorization": f"Bearer {OPENAI_API_KEY}",
        "Content-Type": "application/json",
    }
    ws = await websockets.connect(REALTIME_URL, additional_headers=headers)

# Configure session: 24 kHz PCM in both directions (8 kHz Teler audio is resampled in the bridge)
    session_update = {
        "type": "session.update",
        "session": {
            "modalities": ["audio", "text"],
            "audio": {
                "input": {
                    "format": {"type": "audio/pcm", "rate": 24000}
                },
                "output": {
                    "format": {"type": "audio/pcm", "rate": 24000}
                }
            },
            "turn_detection": {
                "type": "server_vad"
            },
            "instructions": "You are a helpful phone assistant. Be concise."
        }
    }
    await ws.send(json.dumps(session_update))
    return ws

Watch the session.updated event in the response stream before sending audio; the session is not ready until that event arrives.

Step 2: Accept the Teler WebSocket stream and forward audio

Teler connects to your server’s WebSocket endpoint when a call arrives. Each message carries a chunk of raw audio. Forward it to the Realtime API as a base64-encoded input_audio_buffer.append event. Teler sends 16-bit PCM at 8 kHz, so upsample each chunk to 24 kHz before appending it.

import base64
import json
import logging

import numpy as np
from scipy import signal

logger = logging.getLogger(__name__)



class StreamResampler:
    """
    High-quality audio resampling for real-time communication between 16kHz/24kHz and Teler (8kHz).
    """

    def __init__(self):
        self.gemini_input_sample_rate = 16000  #  expects 16kHz input
        self.gemini_output_sample_rate = 24000  # outputs 24kHz
        self.teler_input_sample_rate = 16000  # Teler streams to us at 16kHz
        self.teler_output_sample_rate = 8000   # Teler requires 8kHz from us

    def downsample(self, audio_data: bytes, source_rate: int) -> bytes:
        """
        Downsample audio to Teler's required 8kHz.

        Args:
            audio_data: Raw PCM audio data as bytes
            source_rate: Source sample rate

        Returns:
            Downsampled audio data as bytes (pcm_s16le format at 8kHz)
        """
        try:
            # Convert bytes to numpy array (pcm_s16le format)
            audio_array = np.frombuffer(audio_data, dtype=np.int16)

            # Calculate downsampling factor
            factor = source_rate // self.teler_output_sample_rate

            # Use scipy.decimate for high-quality downsampling
            downsampled_array = signal.decimate(
                audio_array,
                q=factor,
                n=8,
                ftype='iir'
            )

            # Convert back to 16-bit PCM
            downsampled_int16 = downsampled_array.astype(np.int16)

            return downsampled_int16.tobytes()

        except Exception as e:
            logger.error(f"Error downsampling audio: {e}")
            return audio_data

    def upsample(self, audio_data: bytes, target_rate: int) -> bytes:
        """
        Upsample audio from Teler's 16kHz input to target rate.

        Args:
            audio_data: Raw PCM audio data as bytes
            target_rate: Target sample rate

        Returns:
            Upsampled audio data as bytes
        """
        try:
            # Convert bytes to numpy array (pcm_s16le format)
            audio_array = np.frombuffer(audio_data, dtype=np.int16)

            # Calculate upsampling factor
            factor = target_rate / self.teler_input_sample_rate

            # Use scipy.resample for upsampling
            upsampled_array = signal.resample(
                audio_array,
                int(len(audio_array) * factor)
            )

            # Convert back to 16-bit PCM
            upsampled_int16 = upsampled_array.astype(np.int16)

            return upsampled_int16.tobytes()

        except Exception as e:
            logger.error(f"Error upsampling audio: {e}")
            return audio_data


resampler = StreamResampler()


async def forward_teler_audio_to_openai(teler_ws, openai_ws):
    # Loop ends by itself when Teler closes the socket at the end of the call
    async for message in teler_ws:
        data = json.loads(message)
        if data.get("type") == "audio":
            pcm_8k = base64.b64decode(data["data"]["audio_b64"])  # 16-bit PCM, 8 kHz
            pcm_24k = resampler.upsample(pcm_8k, 24000)            # 8 kHz -> 24 kHz
            await openai_ws.send(json.dumps({
                "type": "input_audio_buffer.append",
                "audio": base64.b64encode(pcm_24k).decode("utf-8"),
            }))

The chunk size Teler sends defaults to 400 ms; keep your server’s processing loop faster than that to avoid buffer buildup.

Step 3: Receive model output and resample for the caller

The model streams audio back as response.output_audio.delta events containing base64-encoded 24 kHz PCM. You must downsample this to 8 kHz before sending it back through Teler, because the RTP leg to the caller runs at 8 kHz. Use the StreamResampler class from Step 2, which keeps its filter state between chunks so there are no clicks at chunk boundaries.

async def forward_openai_audio_to_teler(openai_ws, teler_ws):
    # One resampler per call: 24 kHz (Realtime API) -> 8 kHz (Teler)
    downsampler = StreamResampler(24000, 8000)
    chunk_id = 1

    async for message in openai_ws:
        event = json.loads(message)

        if event["type"] == "response.output_audio.delta":
            pcm_24k = base64.b64decode(event["delta"])   # 16-bit PCM, 24 kHz
            pcm_8k = downsampler.process(pcm_24k)         # 24 kHz -> 8 kHz
            await teler_ws.send(json.dumps({
                "type": "audio",
                "audio_b64": base64.b64encode(pcm_8k).decode("utf-8"),
                "chunk_id": str(chunk_id),
            }))
            chunk_id += 1

        elif event["type"] == "response.output_audio.done":
            # One turn complete; no action needed unless you track turn boundaries
            pass

        elif event["type"] == "input_audio_buffer.speech_started":
            # Caller interrupted; flush queued playback
            await teler_ws.send(json.dumps({"type": "clear"}))

The {"type": "clear"} message flushes Teler’s queued playback buffer immediately, which is how barge-in (interruption handling) works on the call leg. Send it as soon as input_audio_buffer.speech_started arrives, not after the model finishes its current turn.

Step 4: Wire both loops together and handle call teardown

Run both forwarding coroutines concurrently so inbound and outbound audio flow in parallel. Cancel both tasks when either connection closes.

async def handle_call(teler_ws, path):
    openai_ws = await open_realtime_session()
    try:
        await asyncio.gather(
            forward_teler_audio_to_openai(teler_ws, openai_ws),
            forward_openai_audio_to_teler(openai_ws, teler_ws),
        )
    finally:
        await openai_ws.close()

import websockets as ws_server

async def main():
    async with ws_server.serve(handle_call, "0.0.0.0", 8765):
        await asyncio.Future()  # run forever

asyncio.run(main())

Point Teler’s media streaming webhook at ws://your-server:8765. See the Teler media streaming documentation for the exact webhook configuration fields and the event schema your server receives. The reference client at openai/openai-realtime-api-beta (last commit October 2025) shows the full Node.js event loop if you prefer JavaScript.

Step 5: Handle DTMF and call control

DTMF (Dual-Tone Multi-Frequency) key presses arrive as separate events in the Teler stream, not as audio. The OpenAI Realtime API added DTMF key-press events for sideband use in the GA release, but the phone-side DTMF bridge logic is still your responsibility. Parse DTMF events from Teler and decide whether to pass them to the model as a conversation.item.create text event or handle them in your own call-control logic (for example, routing to a human agent via a cold transfer). See the Teler call control documentation for hangup, mute, and transfer parameters.

Most teams discover their latency problem is not the model. It is the resampling hop they added between the carrier and the model session, combined with a jitter buffer that was tuned for human-to-human calls rather than for a 400-millisecond chunk pipeline. Fix the buffer sizing first, then look at the model.

– Subhash Kalluri, Founder & CEO, FreJun

What breaks in production when using the OpenAI Realtime API on a phone call?

The failure modes below come from the OpenAI Developer Community and from the SIP incident log. Each was reported at least once; none should be treated as universal.

SymptomLikely causeFix
Latency jumps to nearly a minute after a few minutes of conversationInteraction between input_audio_noise_reduction and semantic_vad or transcription (reported May 2025)Disable noise reduction, or raise semantic_vad.eagerness to high
All WebSocket sessions fail with beta_api_shape_disabledConnection still sends OpenAI-Beta: realtime=v1 after the GA migration (reported May 2026)Remove the beta header and migrate event payloads to the GA shape
SIP calls connect but no audio reaches the callerRTP routing blocked by firewall, NAT, or carrier IP allowlist (reported October 2025)Open RTP ports bidirectionally and verify carrier IP ranges are allowed
Function call arguments appear in the transcript; audio contains unrelated speechTwo combined bugs in function-calling flow (reported February 2025); root cause not isolatedNo fix reported at time of writing
SIP accept returns 404 call_id_not_foundUnresolved; reported September 2026No fix reported at time of writing

The latency spike from noise reduction catches the most teams because it appears only after several minutes of conversation, not during initial testing. A short smoke test passes, the call goes to production, and callers start complaining about a frozen agent mid-conversation. Disable input_audio_noise_reduction first and measure again before tuning VAD settings.

One honest limitation of Teler’s approach: because the telephony layer streams audio in chunks (default 400 ms), your server must send at least 500 ms of audio back per response chunk to avoid choppy playback on the caller’s end. If your model generates very short responses, you may need to buffer output before injecting it into the call. This is a constraint of the chunked streaming model, not something the transport layer resolves automatically.

openai realtime api session config g711 ulaw teler pstn leg panel

Which architecture should you choose for the OpenAI Realtime API on a phone call?

Three architectures are realistic for putting the OpenAI Realtime API on a PSTN call. The right one depends on where you want to own the media path.

ArchitectureMedia terminates atLatency costOperational burdenLock-in
Raw WebSocket backend bridge (this walkthrough)Your serverOne extra hop; resampling adds 5 to 20 msMedium: you own the resampling, jitter buffer, and session lifecycleOpenAI model only
SIP trunk into a media serverYour media server or PBXHigher: SIP signaling, RTP jitter buffer, codec conversion all add upHigh: full SIP stack, NAT traversal, RTP port managementLow: swap models or carriers independently
Managed telephony bridge (Teler + OpenAI Realtime)Teler’s edgeTeler targets sub-100ms packet delivery; resampling still needed on model outputLow: carrier connectivity, number provisioning, and media streaming are managedMedium: Teler handles telephony; model choice stays yours

The raw WebSocket bridge in this walkthrough is the right starting point if you want direct control over the session and are comfortable managing resampling and jitter yourself. Choose the SIP trunk path if you already operate a media server and need full call-control ownership, for example for call recording, multi-party conferencing, or complex IVR routing. The managed bridge is the right choice when you want to ship quickly and the telephony plumbing is not your core product. For teams building AI phone agents where the model behavior is the differentiator, offloading carrier connectivity to a layer like Teler means you spend engineering time on prompts, tools, and session management rather than on SIP NAT traversal.

If you are evaluating the broader landscape of voice infrastructure options, the Top 9 Best Telephony API Providers in the US covers the competitive field, and Building Low-Latency Voice Agents with Elastic SIP Trunking and Real-Time Media APIs goes deeper on the SIP trunk path specifically.

Frequently asked questions

What audio format does the OpenAI Realtime API require for phone call input?

The API accepts audio/pcm at 24 kHz (mono, 16-bit little-endian), audio/pcmu at 8 kHz (G.711 mu-law), and audio/pcma at 8 kHz (G.711 A-law). Teler delivers 16-bit PCM at 8 kHz, so the usual setup is audio/pcm at 24 kHz in both directions, with your bridge resampling 8 kHz to 24 kHz on the way in and 24 kHz to 8 kHz on the way out.

Why does latency spike after several minutes on a live call?

One confirmed cause is the interaction between input_audio_noise_reduction and semantic_vad turn detection or transcription. The delay between end of speech and input_audio_buffer.speech_started can reach nearly a minute in affected sessions. Disabling noise reduction eliminates the spike in the reported case. Context window growth also increases latency on long sessions; the documented limit is 32,768 tokens, and automatic truncation occurs at 28,672 tokens.

Should you use WebSocket or SIP to connect the OpenAI Realtime API to a phone call?

WebSocket is simpler to implement and is the path OpenAI’s own documentation recommends for server-side audio pipelines and phone-call use cases. SIP gives you full call-control ownership and is the right choice if you already operate a media server or need features like multi-party conferencing. SIP adds operational complexity: NAT traversal, RTP port management, and codec negotiation are all your responsibility. For most teams building AI phone agents, the WebSocket path with a managed telephony layer is faster to ship and easier to debug.

What happens to the OpenAI Realtime API session when the caller hangs up?

Teler closes the media WebSocket when the call ends. When your Teler loop exits, close the OpenAI Realtime API WebSocket straight away. If you do not close it, the session continues consuming tokens and running toward the 60-minute session limit. The API does not automatically detect that the phone leg has dropped.

Can you use the OpenAI Realtime API with a model other than GPT-4o?

The Realtime API is OpenAI-model-specific. The documented models include gpt-4o-realtime-preview-2024-12-17 and the gpt-realtime-mini family. There is no documented plug-in path for third-party STT, LLM, or TTS providers within the Realtime API session itself. If you want model-agnostic routing, you need to build your own STT-LLM-TTS pipeline and use the telephony layer for audio transport only. Teler supports that pattern and works with Deepgram, ElevenLabs, and other providers alongside or instead of OpenAI.

What must you build yourself that the OpenAI Realtime API does not provide?

You must supply: phone number provisioning, SIP/PSTN carrier connectivity, codec bridging and resampling, jitter buffering, call control (hangup, transfer, mute), DTMF bridge logic, and session rotation for calls longer than 60 minutes. The Realtime API handles turn detection, transcription, LLM inference, and TTS within the session. Everything outside the model session boundary is your infrastructure problem, or a managed telephony layer’s problem.

How does barge-in work when using Teler with the OpenAI Realtime API?

When the caller speaks while the model is playing audio, the Realtime API emits input_audio_buffer.speech_started. Your server should immediately send {"type": "clear"} to Teler’s WebSocket, which flushes queued playback on the call leg. You can also send response.cancel to the Realtime API to stop the current model turn. The two operations are independent; send both for a clean interruption.

Is the OpenAI Realtime API beta interface still usable in 2026?

No. The beta interface, identified by the OpenAI-Beta: realtime=v1 header, was deprecated in May 2026. Connections using it now fail with beta_api_shape_disabled. Migrate to the GA interface by removing that header and updating your session and event payloads to the GA shape. The GA interface also removed temperature as a model parameter and added idle_timeout_ms under server_vad.

What can you build now with the OpenAI Realtime API on a phone call?

With the walkthrough above, you can connect the OpenAI Realtime API to a live PSTN call, handle barge-in, and manage session teardown on hangup. The one decision that matters most before you go to production is where you want the media to terminate: on your own server, in a media server you operate, or in a managed telephony layer. If the telephony plumbing is not your core product, offloading it to a layer like Teler lets you focus engineering effort on the model behavior, tool definitions, and session management that actually differentiate your application. If you need full call-control ownership or already run a SIP stack, the raw WebSocket bridge gives you that control at the cost of more operational surface. Either way, the OpenAI Realtime API integration itself follows the same event loop: append audio, receive deltas, resample, inject, and handle interruptions. For teams evaluating the full range of voice API providers for AI agents in the US, understanding this audio path is the prerequisite for any honest comparison. Check current Teler pricing for telephony channel and per-minute costs.

About the Author: Subhash Kalluri is the Founder & CEO of FreJun, which he has been building since 2019. With over 8 years in voice communication and SaaS, he works on the problem of getting real-time AI onto live phone calls: raw media streaming, interruption handling, and carrier connectivity. That work became FreJun Teler, FreJun’s programmable voice API for developers building AI phone agents. Connect with him on LinkedIn.

Get started with FreJun today

In this article

Make every voice interaction count

FreJun is a real-time voice platform for automating calls and connecting AI bots.

Popular Articles
Assemblyai.com vs Elevenlabs.io Feature by Feature Comparison for AI Voice Agents

In the quest to build truly intelligent and human-like AI voice agents, developers face two fundamental challenges: understanding what is...

Voice recognition software API running 24/7 across US, UK, India and Singapore time zones.

Quick Answer: To deploy a voice recognition API globally, run speech-to-text in multiple regions, route each caller to the nearest...

Add Voice Bot Conversational AI to Your Web Stack 1 3

Building real-time voice agents is no longer about stitching speech and text together. Modern voice systems expect natural turn-taking, fast...