> ## Documentation Index
> Fetch the complete documentation index at: https://www.vobiz.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# DTMF in Audio Streams — Receive Keypresses and Send Digits

> Receive caller keypresses as dtmf events on your Vobiz Stream WebSocket, and send DTMF digits into the call with sendDTMF to navigate IVRs or enter PINs.

## Overview

Audio streams carry DTMF (touch-tone) digits in both directions:

| Direction | Event | What it does |
| - | - | - |
| Vobiz → App | `dtmf` | Tells your application each time a key is pressed on the call. |
| App → Vobiz | `sendDTMF` | Sends DTMF digits into the call, for example to navigate an external IVR or enter a PIN. |

### When to use DTMF on a stream

* **Keypad input to a voice agent:** let callers press keys ("press 1 for sales") while your agent is listening.
* **IVR navigation:** have an AI agent on an outbound call work through another company's phone menu.
* **PIN and account entry:** let your agent enter account numbers, PINs, or extensions on the caller's behalf.
* **Hybrid input:** accept either speech or keypresses for the same question.

## Receive keypresses: `dtmf` event

When a key is pressed on the call, Vobiz sends a `dtmf` event over the WebSocket. You don't need to configure anything to receive it.

```json dtmf event theme={null}
{
  "event": "dtmf",
  "sequenceNumber": 12,
  "streamId": "b77e037d-4119-44b5-902d-25826b654539",
  "dtmf": {
    "track": "inbound",
    "digit": "5",
    "timestamp": "1763495178506"
  },
  "extra_headers": "{X-VH-agentType: sales}"
}
```

| Field | Description |
| - | - |
| `event` | Always `dtmf`. |
| `sequenceNumber` | Order of this event within the stream, shared with `media` and other events. |
| `streamId` | The stream this event belongs to. |
| `dtmf.track` | Always `inbound`: the key was pressed by the party on the call. |
| `dtmf.digit` | The key that was pressed: one of `0`–`9`, `*`, `#`, `A`, `B`, `C`, `D`. One event per key. |
| `dtmf.timestamp` | When Vobiz received the key, as Unix time in milliseconds, sent as a string. |
| `extra_headers` | The `extraHeaders` set on `<Stream>`, as one string. Each key arrives with an `X-VH-` prefix: `extraHeaders="agentType=sales"` arrives as `"{X-VH-agentType: sales}"`. The string is not JSON, so parse it yourself rather than with a JSON parser. Only present when `extraHeaders` was set. |

> [!NOTE]
>
> `dtmf` events are sent on **every** active stream on the call, including streams with `bidirectional="false"`. If a call has more than one stream, each stream receives its own `dtmf` event for the same keypress.

### What to know about received digits

* **Keypresses still reach the call flow.** A `dtmf` event is a copy. The same digit still goes to anything else listening on the call, such as a [`<Gather>`](https://www.vobiz.ai/docs/xml/gather) running after the stream started.
* **Out-of-band DTMF only.** Vobiz reports keypresses that arrive as RFC 2833 telephone events or SIP INFO, which is how almost all carriers and phones send them. Tones that exist only inside the audio (inband DTMF) are not reported as `dtmf` events. You still receive them as sound in `media` frames.
* **Only while the stream is connected.** Keys pressed before the WebSocket connects, or after the stream stops, are not delivered.
* **No duration.** Each event marks one keypress. Vobiz does not report how long the key was held.

## Send digits: `sendDTMF` event

Send a `sendDTMF` event to play DTMF digits into the call. Vobiz sends them to the other party on the call: on an outbound call to an IVR, the IVR receives them, and on an inbound call, the caller hears them.

> [!NOTE]
>
> **Prerequisite:** `sendDTMF` requires `bidirectional="true"` on the `<Stream>` element. On a unidirectional stream it is rejected.

```json sendDTMF event theme={null}
{
  "event": "sendDTMF",
  "dtmf": "1234#"
}
```

| Attribute | Description |
| - | - |
| `event`  *string*  **Required** | Use `sendDTMF`. |
| `dtmf`  *string*  **Required** | The digits to send, in order. Allowed characters are `0`–`9`, `*`, `#`, and `A`–`D` (lowercase `a`–`d` is accepted). Maximum 99 characters. |
| `streamId`  *string*  Optional | You can include the stream's `streamId` for consistency with other commands. It is not required. |

Digits are sent one after another at standard DTMF timing, the same way as the [Send Digits API](https://www.vobiz.ai/docs/call/dtmf/send-digits.md). Vobiz does not send an acknowledgment when the digits have been sent. If you need to wait for an IVR to respond, listen for its next prompt in the `media` frames.

### Rejected messages

If a `sendDTMF` message is invalid, Vobiz sends no digits and replies with an `incorrectPayload` event that contains the message you sent:

```json incorrectPayload event theme={null}
{
  "event": "incorrectPayload",
  "streamId": "b77e037d-4119-44b5-902d-25826b654539",
  "payload": "{\"event\":\"sendDTMF\",\"dtmf\":\"12x\"}",
  "sequenceNumber": 40
}
```

A `sendDTMF` message is rejected when:

* the stream is not bidirectional,
* `dtmf` is missing or empty,
* `dtmf` is longer than 99 characters, or
* `dtmf` contains a character other than `0`–`9`, `*`, `#`, `A`–`D`. Pause characters (`w`, `W`) and duration suffixes (`@500`) are not supported.

> [!WARNING]
>
> `incorrectPayload` is sent only for the **first** invalid message on a stream, whatever the command. Later invalid messages are dropped without a reply, so validate digits in your application before sending them.

### Things to know when sending digits

* **Sent digits are not echoed back.** Digits you send with `sendDTMF` do not produce `dtmf` events on your stream.
* **Pace multi-step menus yourself.** Send one menu choice, wait for the IVR's next prompt, then send the next. Sending a whole sequence at once can outrun an IVR that is still playing a prompt.
* **Long digit strings take time to play.** Each digit takes a fraction of a second, so a 16-digit account number takes several seconds to finish.

## Implementation examples

### Node.js

```javascript Handle keypresses and navigate an IVR theme={null}
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

const ALLOWED = /^[0-9*#A-D]{1,99}$/i;

function sendDTMF(ws, digits) {
  if (!ALLOWED.test(digits)) {
    throw new Error(`invalid DTMF digits: ${digits}`);
  }
  ws.send(JSON.stringify({ event: 'sendDTMF', dtmf: digits }));
}

wss.on('connection', (ws) => {
  let streamId = null;
  let entered = '';

  ws.on('message', (message) => {
    const data = JSON.parse(message);

    switch (data.event) {
      case 'start':
        streamId = data.start.streamId;
        break;

      case 'dtmf': {
        const digit = data.dtmf.digit;
        if (digit === '#') {
          console.log('Caller entered:', entered);
          entered = '';
        } else {
          entered += digit;
        }
        break;
      }

      case 'media':
        // Pass audio to your speech pipeline. When the IVR you called
        // says "press 2 for billing", choose an option:
        // sendDTMF(ws, '2');
        break;

      case 'incorrectPayload':
        console.error('Vobiz rejected a command:', data.payload);
        break;
    }
  });
});
```

### Python

```python Handle keypresses and send digits with asyncio theme={null}
import asyncio
import json
import re
import websockets

ALLOWED = re.compile(r'^[0-9*#A-Da-d]{1,99}$')

async def send_dtmf(websocket, digits):
    if not ALLOWED.match(digits):
        raise ValueError(f"invalid DTMF digits: {digits}")
    await websocket.send(json.dumps({'event': 'sendDTMF', 'dtmf': digits}))

async def handle_stream(websocket):
    entered = ''
    async for message in websocket:
        data = json.loads(message)

        if data['event'] == 'dtmf':
            digit = data['dtmf']['digit']
            if digit == '#':
                print(f"Caller entered: {entered}")
                entered = ''
            else:
                entered += digit

        elif data['event'] == 'media':
            # Pass audio to your speech pipeline. To enter an account
            # number when the IVR asks for it:
            # await send_dtmf(websocket, '4021#')
            pass

        elif data['event'] == 'incorrectPayload':
            print(f"Vobiz rejected a command: {data['payload']}")

async def main():
    async with websockets.serve(handle_stream, '0.0.0.0', 8080):
        await asyncio.Future()

if __name__ == '__main__':
    asyncio.run(main())
```

## Related

* [Stream events overview](https://www.vobiz.ai/docs/xml/stream/stream-events.md) - every event sent over the stream's WebSocket.
* [Initiate a Stream](https://www.vobiz.ai/docs/xml/stream/initiate.md) - `<Stream>` attributes, including `bidirectional` and `extraHeaders`.
* [Send digits on an active call](https://www.vobiz.ai/docs/call/dtmf/send-digits.md) - send DTMF with the REST API instead of the WebSocket.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.