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:- WebSocket connection — Connect to the voice endpoint and manage the message protocol
- Audio capture — Record microphone input as 16-bit mono PCM at 16kHz
- Audio playback — Play the agent’s response audio (16-bit mono PCM at 24kHz)
- 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)
UseAVAudioEngine to capture microphone audio and convert it to 16-bit PCM:
3. Audio Playback
UseAVAudioPlayerNode 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 yourInfo.plist:
Interruption Handling
When the user starts speaking while the agent is responding, send aninterrupt message to cut off the agent’s response. You can detect this using Voice Activity Detection (VAD) or by monitoring microphone input levels.
For push-to-talk or on-device end-of-turn, start the session with voice_config.turn_end_mode set to client, then send end_turn after the last PCM chunk of every utterance is flushed. Client mode disables the server silence timer. Keep the default server mode for hands-free clients that need silence detection; they may still send end_turn as an early-close hint.
This is not barge-in: interrupt stops the agent; end_turn closes the user turn. Do not enable client mode or send end_turn until the backend that understands them is deployed.
Error Handling & Reconnection
The WebSocket connection can drop due to network issues. In production, implement:- Automatic reconnection with exponential backoff
- Graceful handling of
URLSessionWebSocketTaskdelegate errors - Audio session interruption handling (e.g., phone calls)
Thread Safety
TheURLSessionWebSocketTask delivers callbacks on the delegate queue. Make sure to dispatch UI updates and audio operations to the appropriate threads.