DOCUMENTATION

mod_audio_stream

FreeSWITCH API, WebSocket protocol, bidirectional audio and playback control.

GETTING STARTED

Overview

mod_audio_stream is a native FreeSWITCH module that streams channel audio as L16 to a WebSocket endpoint and supports bidirectional audio playback. It uses libwsc, a lightweight C++ WebSocket client based on libevent.

This reference describes the commercial version 1.1.0.

  • New playback mix mode for bridged calls. Returned WebSocket audio can now be mixed with the existing call audio without replacing it. Each leg of a bridged call can run its own independent stream, with optional gain control for the returned audio. The existing direct playback mode remains the default and is fully backward compatible.

  • Named pipe (FIFO) output is now available for returned playback audio. It provides local PCM16 audio output with optional sample-rate conversion and can be started or stopped at runtime.

  • Playback audio is written through the FreeSWITCH session media pipeline, making it available to media bugs and native recording tools. This allows uuid_record to capture both caller audio and streamed playback in a single recording.

GETTING STARTED

Real-Time Streaming Guidelines

Forward audio as soon as it becomes available. Do not wait to collect multiple provider responses before forwarding them. This applies to both raw binary and JSON/Base64 audio. The module manages its own playback queue.

Avoid running FreeSWITCH speak or playback on the same channel during active streaming. Blocking media operations can interrupt the continuous media flow and prevent timely audio delivery. Use the module’s automatic playback interface instead.

See RAW Binary Audio for packet size and timing requirements.

GETTING STARTED

Architecture

FreeSWITCH → mod_audio_stream → WebSocket server

The module is a WebSocket client, not a WebSocket server. Your endpoint receives channel audio and can return audio and text messages. A provider-specific middleware is required when the provider protocol differs from the module protocol.

GETTING STARTED

Installation

Prebuilt packages are available from the Downloads page. See the Installation Guide.

For source builds:

Dependencies

It requires libfreeswitch-dev, libssl-dev, zlib1g-dev, libspeexdsp-dev, and libevent-dev on Debian/Ubuntu, which are regular packages for FreeSWITCH installation.

Optional: Opus support (returned audio)

Support for Opus as a returned audio format is optional and disabled by default.

To enable Opus support, the following additional dependencies are required:

  • libopus0 (runtime)
  • libopus-dev (build)

On Debian/Ubuntu:

BASH
sudo apt install libopus0 libopus-dev

To build with OPUS support add -DUSE_OPUS=ON to cmake line.

Building

After cloning please execute: git submodule init and git submodule update to initialize the submodule.

Custom path

If you built FreeSWITCH from source, eq. install dir is /usr/local/freeswitch, add path to pkgconfig:

TEXT
export PKG_CONFIG_PATH=/usr/local/freeswitch/lib/pkgconfig

To build the module, from the cloned repository directory:

TEXT
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make
sudo make install

TLS is OFF by default. To build with TLS support add -DUSE_TLS=ON to cmake line.

DEB Package

To build a .deb package after building the module, run:

TEXT
cpack -G DEB

The generated Debian package (.deb) will be placed in the top-level _packages directory of your project.

Scripted Build & Installation

TEXT
sudo apt-get -y install git \
    && cd /usr/src/ \
    && git clone https://github.com/amigniter/mod_audio_stream.git \
    && cd mod_audio_stream \
    && sudo bash ./build-mod-audio-stream.sh
GETTING STARTED

Licensing

This documentation covers the commercial build. See Pricing and Downloads for available editions. Features described here should not be assumed to be available in every Community build.

CONFIGURATION

Channel Variables

The following channel variables can be used to fine tune websocket connection and also configure mod_audio_stream logging:

Variable Description Default
STREAM_MESSAGE_DEFLATE true or 1, disables per message deflate off
STREAM_HEART_BEAT number of seconds, interval to send the heart beat off
STREAM_SUPPRESS_LOG true or 1, suppresses printing to log off
STREAM_BUFFER_SIZE buffer duration in milliseconds, divisible by 20 20
STREAM_EXTRA_HEADERS JSON object for additional headers in string format none
STREAM_NO_RECONNECT true or 1, disables automatic websocket reconnection off
STREAM_SAMPLE_RATE sample rate of the returned audio none
STREAM_PLAYBACK true or 1, enables automatic playback off
STREAM_PLAYBACK_MODE playback mode: direct or mix direct
STREAM_PLAYBACK_GAIN gain applied to returned audio in mix mode 1.0
  • Per message deflate compression option is enabled by default. It can lead to a very nice bandwidth savings. To disable it set the channel var to true|1.
  • Heart beat, sent every xx seconds when there is no traffic to make sure that load balancers do not kill an idle connection.
  • Suppress parameter is omitted by default(false). All the responses from websocket server will be printed to the log. Not to flood the log you can suppress it by setting the value to true|1. Events are fired still, it only affects printing to the log.
  • Buffer Size actually represents a duration of audio chunk sent to websocket. If you want to send e.g. 100ms audio packets to your ws endpoint you would set this variable to 100. If ommited, default packet size of 20ms will be sent as grabbed from the audio channel (which is default FreeSWITCH frame size)
  • Extra headers should be a JSON object with key-value pairs representing additional HTTP headers. Each key should be a header name, and its corresponding value should be a string.
    JSON
    {
        "Header1": "Value1",
        "Header2": "Value2",
        "Header3": "Value3"
    }
  • Websocket automatic reconnection is on by default. To disable it set this channel variable to true or 1.
  • Enables automatic playback on the channel (audio is streamed from) from the json response. Please see more on the play event.
  • STREAM_SAMPLE_RATE is a required channel variable that tells the module the sample rate of the returned audio only when raw binary stream is used as the response format. This ensures correct playback behavior. See RAW Binary Audio for more details.
  • STREAM_PLAYBACK_MODE controls how returned audio is delivered when automatic playback is enabled:
    • direct (default) uses the standard playback path and preserves the existing playback behavior.
    • mix mixes returned audio with the audio already being written to the channel. This is useful for bridged calls where the original call audio must continue while external audio is injected into either leg.
  • STREAM_PLAYBACK_GAIN controls the level of returned audio in mix mode without changing the level of the original channel audio. The default value is 1.0. For example, 0.5 reduces the returned audio level, 0.0 mutes returned audio, and values greater than 1.0 amplify it.
CONFIGURATION

WebSocket Connection

Use ws:// or wss:// in the start command. TLS support for source builds requires -DUSE_TLS=ON. Additional HTTP headers can be supplied through STREAM_EXTRA_HEADERS, for example:

JSON
{"Authorization":"Bearer YOUR_TOKEN"}

Heartbeat and reconnection behavior are controlled through the channel variables above.

FREESWITCH API

start

TEXT
uuid_audio_stream <uuid> start <wss-url> <mix-type> <sampling-rate> <metadata>

Attaches a media bug and starts streaming audio (in L16 format) to the websocket server. FS default is 8k. If sampling-rate is other than 8k it will be resampled.

  • uuid - Freeswitch channel unique id
  • wss-url - websocket url ws:// or wss://
  • mix-type - choice of
    • "mono" - single channel containing caller's audio
    • "mixed" - single channel containing both caller and callee audio
    • "stereo" - two channels with caller audio in one and callee audio in the other.
  • sampling-rate - choice of
    • "8k" = 8000 Hz sample rate will be generated
    • "16k" = 16000 Hz sample rate will be generated
  • metadata - (optional) a valid utf-8 text to send. It will be sent the first before audio streaming starts.
FREESWITCH API

send_text

TEXT
uuid_audio_stream <uuid> send_text <metadata>

Sends a text to the websocket server. Requires a valid utf-8 text.

FREESWITCH API

stop

TEXT
uuid_audio_stream <uuid> stop <metadata>

Stops audio stream and closes websocket connection. If metadata is provided it will be sent before the connection is closed.

FREESWITCH API

pause / resume

TEXT
uuid_audio_stream <uuid> pause

Pauses audio stream

TEXT
uuid_audio_stream <uuid> resume

Resumes audio stream

FREESWITCH API

break

If you want to stop the playback at certain point (or based on the tracked sequence) you can do it by calling the break API method:

TEXT
uuid_audio_stream <uuid> break

The command immediately interrupts the current playback and clears queued playback audio. The WebSocket stream remains active, and playback resumes when new audio is received.

In mix mode, breaking playback affects only the returned WebSocket audio. The original bridged call audio continues normally.

FREESWITCH API

pipe

See Named Pipe (FIFO) for the complete API and examples.

AUDIO STREAMING

Audio Formats

Outbound audio is L16. The start command selects mono (caller), mixed (caller and callee in one channel), or stereo (separate caller and callee channels). Automatic playback requires a mono stream. The documented outbound sample rates are 8k and 16k; returned PCM audio has its own sample rate.

STREAM_BUFFER_SIZE controls outbound chunk duration in milliseconds, divisible by 20 (default 20).

BIDIRECTIONAL PLAYBACK

Overview

  • Playback feature allows continuous forward streaming while the playback runs independently.
  • It is a full-duplex stream between the caller and the websocket.
  • It supports base64 encoded audio as well as the raw binary stream from the websocket.

To enable this 'two-way-audio and auto playback' feature please set "STREAM_PLAYBACK" channel variable to true or 1.

  • STREAM_PLAYBACK channel var is required for either JSON base64 encoded audio or RAW stream.
  • It is required to have a single channel when calling uuid_audio_stream API from the module.
BIDIRECTIONAL PLAYBACK

JSON / Base64 Audio

Expected JSON response format is:

JSON
{
  "type": "streamAudio",
  "data": {
    "audioDataType": "raw",
    "sampleRate": 8000,
    "audioData": "base64 encoded audio"
  }
}

The supported types (audio formats) are "raw", "pcmu", "pcma" and "opus". Please make sure to properly set the sample rate. For PCMU/PCMA it is 8000 whereas the RAW format can have variable sample rate, so it is required to set it accordingly. RAW format needs to be 16-bit (L16) and properly aligned.

Incoming audio will be played back to the caller as it arrives, either in whole or in sequences. The audio data will be delivered all at once (as a single unit) or in chunks (sequentially), and it will be played back immediately upon arrival.

BIDIRECTIONAL PLAYBACK

PCMU / PCMA Fast Path

PCMU and PCMA are also offered as the FAST PATH if the engine supports them. To benefit from the FAST PATH—where any resampling or transcoding is skipped—users must return PCMA or PCMU and the channel itself must already be using that same codec. If the channel is using another codec and PCMU/PCMA is returned, the audio will not be played; in that case, users should return raw instead.

BIDIRECTIONAL PLAYBACK

Opus

OPUS requirements:

  • raw Opus frames (no container)
  • mono
  • 48 kHz
  • base64-encoded payload
  • expected frame size is 20 ms per packet.

Does not accept Ogg/WebM/Matroska streams. Only raw Opus packets are supported.

The module processes returned audio using a 20 ms media tick. For best results, Opus frames should be generated at 20 ms (e.g. 960 samples at 48 kHz). Larger or variable frame sizes may increase latency or cause uneven playback.

BIDIRECTIONAL PLAYBACK

RAW Binary Audio

Audio Format

  • Encoding: 16-bit linear PCM (L16)
  • Channels: Mono (single channel)
  • Endianness: Little-endian (typical for x86/x64 systems)

When to Use RAW Binary Streaming

RAW binary mode is intended for real-time, frame-oriented audio streaming.

Binary WebSocket messages should contain small, consecutive audio chunks, similar to the audio frames produced by FreeSWITCH during outbound streaming. For example, 20 ms of 8 kHz, 16-bit mono PCM audio contains 160 samples, or 320 bytes.

Incoming RAW binary audio is accumulated internally before being passed to the playback queue. A single WebSocket binary message must not exceed 8192 bytes.

RAW binary mode is therefore best suited for providers or applications that produce audio incrementally as a continuous real-time stream.

If your application produces larger or arbitrarily sized audio chunks, use the JSON audio interface instead. JSON audio messages are passed directly to the playback queue and are better suited for chunk-oriented audio delivery.

In short:

Input format Recommended use
RAW binary Small, continuous, frame-oriented real-time audio chunks
JSON audio Larger or arbitrarily sized audio responses/chunks

Sample Rate Configuration

The module requires knowledge of the stream's sample rate. You can specify this in one of two ways (prioritized in this order):

  1. JSON Metadata Message (Highest Priority)

    Send this as the first message over the WebSocket before streaming raw binary data:

    JSON
      {
        "type": "rawAudio",
        "data": {
          "sampleRate": 8000 // Supported rates: 8000, 16000, 24000, 48000, etc.
        }
      }
    • Overrides any pre-set channel variable.
    • Must precede the binary stream.
  2. Channel Variable (STREAM_SAMPLE_RATE)

    Set this variable before starting playback:

    XML
    <action application="set" data="STREAM_SAMPLE_RATE=8000"/>
    • Fallback if no JSON metadata is provided.
Packetization and timing

Send small consecutive chunks, preferably 20 ms, without waiting to batch provider responses. Maintain sufficient delivery rate to avoid playback underflow. A single binary message must not exceed 8192 bytes. If no data arrives for 100 ms, the module treats the segment as complete and resumes playback when new data arrives.

BIDIRECTIONAL PLAYBACK

Direct Mode

direct is the default playback mode and preserves the existing mod_audio_stream playback behavior.

TEXT
STREAM_PLAYBACK=true
STREAM_PLAYBACK_MODE=direct

STREAM_PLAYBACK_MODE may be omitted when using direct playback:

TEXT
STREAM_PLAYBACK=true

In direct mode, returned WebSocket audio is played directly to the channel on which the stream is running. This is the standard single-leg playback mode.

Direct playback is intended for scenarios where returned audio should be played to a single channel. It does not mix returned audio with the existing audio of a bridged call.

BIDIRECTIONAL PLAYBACK

Mix Mode

For bridged calls, mix mode allows returned WebSocket audio to be added to the existing audio being delivered to a selected call leg:

TEXT
STREAM_PLAYBACK=true
STREAM_PLAYBACK_MODE=mix

The existing bridged audio continues normally while returned WebSocket audio is mixed into that leg.

For example, in a bridged call between A and B:

TEXT
A <------------------------------ B
          bridged audio

A <---- bridged audio + WS audio

If mix playback is enabled on leg A, A hears both the original audio from B and the returned WebSocket audio. B continues to hear the original audio from A normally.

Each leg can also run its own independent WebSocket stream:

TEXT
                  WebSocket A
                      |
                      v
A <---- audio from B + returned audio A

B <---- audio from A + returned audio B
                      ^
                      |
                  WebSocket B

This allows returned audio to be independently mixed into either one leg or both legs of a bridged call.

BIDIRECTIONAL PLAYBACK

Playback Gain

The level of returned audio in mix mode can be controlled with STREAM_PLAYBACK_GAIN:

TEXT
STREAM_PLAYBACK=true
STREAM_PLAYBACK_MODE=mix
STREAM_PLAYBACK_GAIN=0.5

The default gain is:

TEXT
STREAM_PLAYBACK_GAIN=1.0

STREAM_PLAYBACK_GAIN affects only the returned WebSocket audio. It does not modify the level of the original bridged audio.

Examples:

Value Effect
0.0 Returned audio is muted
0.5 Returned audio is attenuated
1.0 Original returned-audio level (default)
2.0 Returned audio is amplified

Values greater than 1.0 may cause clipping when the combined audio level exceeds the PCM16 range.

STREAM_PLAYBACK_GAIN applies to mix mode only.

BIDIRECTIONAL PLAYBACK

Playback Queue

Engines like OpenAI real-time API or ElevenLabs ConversationalAI may return multiple audio responses at once (within a second or even faster). The module will queue all incoming responses internally in its playback queue and play them in order, ensuring smooth, continuous audio playback without gaps.

See playback events for progress tracking.

BIDIRECTIONAL PLAYBACK

Interruption & Barge-in

Use break to clear queued playback without closing the WebSocket. The application can trigger this when it detects an interruption. In mix mode the original bridged audio continues.

RECORDING & AUDIO OUTPUT

Native FreeSWITCH Recording

Playback audio is written through the FreeSWITCH session media pipeline, making it available to media bugs and native recording tools. This allows uuid_record to capture both caller audio and streamed playback in a single recording.

The module-specific recording API is deprecated. Please use the native FreeSWITCH uuid_record API, which can record both channel audio and returned WebSocket audio in a single unified recording.

RECORDING & AUDIO OUTPUT

Named Pipe (FIFO)

The pipe is a tap of the returned playback audio; it does not replace normal playback to the caller.

Returned playback audio can also be exposed through a local named pipe (FIFO). This allows another local application or process to consume the playback audio independently while it is being played to the caller.

The pipe output is always:

  • Encoding: 16-bit linear PCM (PCM16)
  • Channels: Mono
  • Endianness: Little-endian

To start pipe output:

TEXT
uuid_audio_stream <uuid> pipe start <path> [sample-rate]

For example:

TEXT
uuid_audio_stream <uuid> pipe start /tmp/mod_audio_stream.pipe

By default, the pipe uses the actual sample rate of the FreeSWITCH channel.

An optional output sample rate can be specified:

TEXT
uuid_audio_stream <uuid> pipe start /tmp/mod_audio_stream.pipe 16000

Supported output sample rates are 8000, 16000, 24000, 32000 and 48000 Hz. When the requested rate differs from the channel rate, the audio is resampled before being written to the pipe.

To stop pipe output:

TEXT
uuid_audio_stream <uuid> pipe stop

If the FIFO does not exist, the module creates it and removes it when pipe output is stopped. An existing FIFO can also be used; in that case, the module does not remove it.

The pipe is non-blocking and is intended for real-time audio consumption. If no reader is connected, audio is not buffered for later delivery. A reader that connects later will receive audio from that point forward.

For example, the raw PCM output can be captured with:

BASH
cat /tmp/mod_audio_stream.pipe > /tmp/playback.raw

and played as 16 kHz PCM16 mono audio with:

BASH
ffplay -f s16le -ar 16000 -ac 1 /tmp/playback.raw
EVENTS

Overview

Module will generate the following event types:

  • mod_audio_stream::json
  • mod_audio_stream::connect
  • mod_audio_stream::disconnect
  • mod_audio_stream::error
  • mod_audio_stream::play
  • mod_audio_stream::playback
EVENTS

json

Message received from websocket endpoint. Json expected, but it contains whatever the websocket server's response is.

Freeswitch event generated

Name: mod_audio_stream::json Body: WebSocket server response

EVENTS

connect

Successfully connected to websocket server.

Freeswitch event generated

Name: mod_audio_stream::connect Body: JSON

JSON
{
	"status": "connected"
}
EVENTS

disconnect

Disconnected from websocket server.

Freeswitch event generated

Name: mod_audio_stream::disconnect Body: JSON

JSON
{
	"status": "disconnected",
	"message": {
		"code": 1000,
		"reason": "Normal closure"
	}
}
  • code: <int>
  • reason: <string>
EVENTS

error

There is an error with the connection. Multiple fields will be available on the event to describe the error.

Freeswitch event generated

Name: mod_audio_stream::error Body: JSON

JSON
{
	"status": "error",
	"message": {
		"retries": 1,
		"error": "Expecting status 101 (Switching Protocol), got 403 status connecting to wss://localhost, HTTP Status line: HTTP/1.1 403 Forbidden\r\n",
		"wait_time": 100,
		"http_status": 403
	}
}
  • retries: <int>, error: <string>, wait_time: <int>, http_status: <int>
EVENTS

play

Name: mod_audio_stream::play Body: JSON

Automatic playback: off (default)

STREAM_PLAYBACK: false

When automatic playback is disabled, the WebSocket server can return a JSON object containing base64-encoded audio for user playback. To use this feature, the response must adhere to the following format:

JSON
{
  "type": "streamAudio",
  "data": {
    "audioDataType": "raw",
    "sampleRate": 8000,
    "audioData": "base64 encoded audio"
  }
}
  • audioDataType: <raw|wav|mp3|ogg>

The module generates an event (subclass: mod_audio_stream::play) that mirrors the data element with an additional file field, indicating the file path:

JSON
{
  "audioDataType": "raw",
  "sampleRate": 8000,
  "file": "/path/to/the/file"
}

The file is saved in FreeSWITCH's designated temporary directory, typically /tmp. On modern Linux distributions, /tmp is often mounted as tmpfs, meaning the file resides in memory, allowing faster read and write operations.

Automatic playback enabled
  • Event Type: CUSTOM
  • Event Subclass: mod_audio_stream::play

For each incoming JSON response with base64 audio, the module will fire an event containing the "data" object (excluding the "audioData" field). For example:

JSON
{
    "audioDataType": "raw",
    "sampleRate": 8000,
    // <-- you can inject any element, or multiple objects here
}

If you need any additional metadata for sequence tracking or further processing, simply inject it into the "data" object of your JSON response—the module will forward it in the event.

logging

If printing to the log is not suppressed, response printed to the console will look the same as the event. The original response containing base64 encoded audio is replaced because it can be quite huge.

All the files generated by this feature will reside at the temp directory and will be deleted when the session is closed.

EVENTS

playback

  • Event Type: CUSTOM
  • Event Subclass: mod_audio_stream::playback

When each audio response is played from the internal playback queue, the module will fire a chunk_played event to help you track progress and fine-tune your logic:

JSON
{
  "event": "chunk_played",
  "seq": 12,
  "size": 320,
  "remaining": 5
}

Once the playback queue has been fully drained, a queue_completed event is emitted:

JSON
{
  "event": "queue_completed",
  "total_chunks": 12
}

Note: After the final chunk_played event, the "remaining" field will be 0. You can use this alone to detect that playback is complete and skip the queue_completed event—choose whichever fits your application logic best.

INTEGRATION

WebSocket Middleware

A: The module is designed to be independent and provider-agnostic, meaning it does not directly integrate with specific APIs like ChatGPT's real-time API. Instead, it expects a standardized JSON format for incoming audio data. This design ensures flexibility and adaptability, allowing the module to work with any speech-to-speech engine or provider. However, since the module requires this specific JSON format, a proxy is needed to act as an intermediary. The proxy handles communication with the provider's API (e.g., ChatGPT), transforms the data into the required JSON format, and delivers it to the module. This way, you can switch providers or engines without modifying the module itself, making the system modular.

If you obtain the source code and prefer not to use the standardized JSON approach, you can easily modify the expected format to suit your specific requirements. This allows you to eliminate the need for a proxy and enable direct communication between the module and your engine/provider via WebSocket.

By adjusting the message-handling logic in the source code, you can implement a custom integration that communicates directly with the API of your choice. This flexibility ensures the module can be seamlessly adapted to any system or provider, offering maximum control over the communication protocol and data format.

For direct integration with supported realtime AI providers, see mod_realtime_ai.

INTEGRATION

Usage Examples

Example commands in FreeSWITCH CLI (replace <uuid> with the channel UUID):

TEXT
uuid_setvar <uuid> STREAM_PLAYBACK true
uuid_audio_stream <uuid> start ws://127.0.0.1:8080 mono 8k
uuid_audio_stream <uuid> break
uuid_audio_stream <uuid> stop

For bridged calls, set STREAM_PLAYBACK_MODE=mix on the selected leg before starting its stream.

HELP

Troubleshooting

No returned audio

Check STREAM_PLAYBACK, mono mode, audio format and sample rate. For PCMU/PCMA, verify that the channel codec matches.

Choppy playback

Check binary message size, delivery cadence and blocking media operations. See Real-Time Streaming Guidelines.

Connection failure

Inspect mod_audio_stream::error, the endpoint URL, TLS support and required HTTP headers.

FIFO has no audio

Check that a reader is connected. The FIFO does not retain audio for future readers.