Skip to main content
This guide walks through building a voice assistant in a Swift iOS app. You’ll capture microphone audio, stream it to the Datagrid Voice API over a WebSocket, and play back the agent’s audio responses in real time.
This guide uses the direct WebSocket approach — connecting straight to wss://api.datagrid.com/ws/voice. You can also use the REST endpoint (POST /v1/voice) to get a pre-built WebSocket URL and start message first.

Overview

The integration has four parts:
  1. WebSocket connection — Connect to the voice endpoint and manage the message protocol
  2. Audio capture — Record microphone input as 16-bit mono PCM at 16kHz
  3. Audio playback — Play the agent’s response audio (16-bit mono PCM at 24kHz)
  4. UI — A simple button to start/stop the conversation

1. WebSocket Client

Create a class that manages the WebSocket connection and message routing:

2. Audio Capture (Microphone)

Use AVAudioEngine to capture microphone audio and convert it to 16-bit PCM:

3. Audio Playback

Use AVAudioPlayerNode to play back the agent’s PCM audio in real time:

4. Putting It All Together

Here’s a SwiftUI view that ties everything together:

Important Notes

Audio Formats

  • Microphone input: 16-bit mono PCM, 16kHz sample rate
  • Agent response: 16-bit mono PCM, 24kHz sample rate

Permissions

Add the following to your Info.plist:

Interruption Handling

When the user starts speaking while the agent is responding, send an interrupt message to cut off the agent’s response. You can detect this using Voice Activity Detection (VAD) or by monitoring microphone input levels.

Error Handling & Reconnection

The WebSocket connection can drop due to network issues. In production, implement:
  • Automatic reconnection with exponential backoff
  • Graceful handling of URLSessionWebSocketTask delegate errors
  • Audio session interruption handling (e.g., phone calls)

Thread Safety

The URLSessionWebSocketTask delivers callbacks on the delegate queue. Make sure to dispatch UI updates and audio operations to the appropriate threads.