Blog · · 4 min read

Adding Voice AI to Web and Mobile Apps with WebRTC

Add voice AI to web and mobile apps over WebRTC, keeping the API key on your server and giving the client a short-lived token. Flow, server and browser code included.

Key points

  • To add voice AI to a web or mobile app, your server creates a session with its API key and passes only a short-lived client token to the app, and the API key never leaves the server.
  • The app sends a WebRTC offer with its microphone track, plus the token, to the voice server and connects using the answer it gets back.
  • Tokens are short-lived and single-use, so starting over means creating a new session, and results are fetched by session ID through the same API as phone calls.

Voice AI in a browser or mobile app runs over WebRTC. The part that matters most is credentials: your API key stays on your server, and the app only ever sees a short-lived token your server minted for one conversation. The app sends a WebRTC offer with that token to the voice server, applies the answer, and audio starts flowing.

Why WebRTC

You need to send microphone audio and play back the agent's voice with as little delay as possible. WebRTC is built into every modern browser and handles the hard parts, including audio codecs, packet loss and echo cancellation (MDN WebRTC API). You can stream raw audio over a WebSocket instead, but then echo cancellation and jitter handling are your problem.

Split the keys

Assume anything shipped to a browser or an app binary can be extracted. So use two different credentials with different scopes:

Credential Lives on Can do
API key Your server only Everything in the environment: create sessions, read results, change configs
Client token The client, for one conversation Connect audio for that one session, nothing else

Make the token short-lived and single-use, so a leaked token is worth very little. Require your own user login before creating a session and strangers can't start conversations on your bill either.

The connection flow

  1. The user taps "Talk."
  2. The app asks your server for a session (authenticated with your own login).
  3. Your server creates a session on the voice platform with its API key and gets back a token and a connection URL.
  4. Your server returns only the token and the URL to the app.
  5. The app gets microphone permission, creates a WebRTC offer and posts it with the token to the URL.
  6. The app applies the answer and audio starts.
  7. When the conversation ends, your server fetches the result through the API.

Server code

Your server creates the session. With voicast that's POST /v1/sessions.

ts
// Your server (Node.js 18+, Express)
app.post('/api/voice-session', requireLogin, async (req, res) => {
  const r = await fetch('https://api.voicast.jp/v1/sessions', {
    method: 'POST',
    headers: { authorization: `Bearer ${process.env.VOICAST_API_KEY}`, 'content-type': 'application/json' },
    body: JSON.stringify({ tenant_id: req.user.voicastTenantId }), // the user's organization
  });
  if (!r.ok) return res.status(r.status === 402 ? 402 : 502).json({ error: 'session_failed' });
  const s = await r.json();
  // Never return the API key. The client needs exactly these three values.
  res.json({ id: s.id, client_token: s.client_token, webrtc_url: s.webrtc_url });
});

The client_token (vct_…) expires after 2 minutes and works once, so the client should connect immediately.

Browser code

In the browser, the voicast SDK (voicast/web) is the quickest route, and clients that support RTVI also work. If you'd rather use only browser APIs, here's a minimal version:

ts
async function startVoice(audioEl: HTMLAudioElement) {
  const s = await (await fetch('/api/voice-session', { method: 'POST' })).json();

  const mic = await navigator.mediaDevices.getUserMedia({
    audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
  });
  const pc = new RTCPeerConnection(); // add STUN/TURN to iceServers if your network needs them
  pc.addTransceiver(mic.getAudioTracks()[0], { direction: 'sendrecv' });
  pc.addTransceiver('video', { direction: 'recvonly' });
  pc.ontrack = (e) => {
    if (e.track.kind === 'audio') {
      audioEl.srcObject = e.streams[0] ?? new MediaStream([e.track]);
      audioEl.play().catch(() => {});
    }
  };

  // Data channel for RTVI messages; ping regularly to keep the connection alive
  const dc = pc.createDataChannel('chat', { ordered: true });
  dc.onopen = () => {
    dc.send(JSON.stringify({ label: 'rtvi-ai', type: 'client-ready', id: crypto.randomUUID(), data: { version: '1.0.0', about: { library: 'my-app' } } }));
    setInterval(() => dc.readyState === 'open' && dc.send(`ping: ${Date.now()}`), 1000);
  };

  await pc.setLocalDescription(await pc.createOffer());
  await new Promise<void>((done) => {
    if (pc.iceGatheringState === 'complete') return done();
    pc.addEventListener('icegatheringstatechange', () => pc.iceGatheringState === 'complete' && done());
    setTimeout(done, 2500); // don't wait forever for candidates
  });

  const r = await fetch(s.webrtc_url, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ sdp: pc.localDescription!.sdp, type: pc.localDescription!.type, token: s.client_token }),
  });
  if (r.status === 403) throw new Error('Token is invalid, expired or already used');
  const answer = await r.json(); // { sdp, type, pc_id }
  await pc.setRemoteDescription({ type: answer.type, sdp: answer.sdp });
  return { pc, sessionId: s.id, pcId: answer.pc_id };
}

A few practical notes:

  • Start playback inside the click handler. Browsers, Safari especially, block audio that doesn't follow a user gesture. Call audioEl.play() while handling the "Talk" tap.
  • Keep echo cancellation on. Without it the mic picks up the agent's voice from the speaker and the agent interrupts itself (barge-in and turn-taking).
  • Trickle late ICE candidates with PATCH and { pc_id, candidates }. The example above takes the simpler route of waiting for gathering before sending the offer.

Mobile apps

The flow is identical on iOS and Android: the app fetches a token and URL from your server and connects over WebRTC. Never embed the API key in the app. App binaries can be unpacked, and a key leaked from a store build stays exposed until you rotate it and every user updates. Remember the microphone permission strings too, such as NSMicrophoneUsageDescription on iOS.

Reconnecting and results

Tokens are single-use, so starting a conversation over means creating a new session. If the network changes mid-conversation, you can reconnect the same peer by sending an offer with pc_id and restart_pc.

When the conversation ends, your server fetches the result by session id:

sh
curl -s https://api.voicast.jp/v1/calls/by-provider/$SESSION_ID \
  -H "authorization: Bearer $VOICAST_API_KEY"

You get the outcome, collected fields, duration and cost, with channel set to web. Post-call webhooks are the same as for phone calls.

Doing this with voicast

In voicast, web and app conversations use the same agents and tenants as phone calls; POST /v1/sessions is all it takes to connect them. Pass agent_id to use a different config from the tenant's default, for example a dedicated tutor persona (building an English conversation practice app). With output: 'text', voicast doesn't speak; it sends reply text over the data channel as RTVI server-message events so you can pair it with an avatar or another speaker (combining avatars with voice AI).

FAQ

What if a client token leaks?

A token can only connect audio for its own session, expires after 2 minutes and stops working after one use. Requiring your own login before creating sessions, and rate-limiting how many a user can create, closes the remaining gap.

Can't the browser call the voicast API directly?

It would mean putting your API key in the browser, so don't. The API key can change configs and read conversation records across the whole environment. Always create sessions on your server.

Should web and phone use separate agent configs?

They can share one. If the web experience differs, say you can show text on screen and don't need to collect a phone number, create a web-specific agent and select it with agent_id when creating the session.

Related posts