This guide focuses on the live browser session: connection states, microphone capture, playback, and recovery. For server-side architecture and request boundaries, start with the API integration guide.
A Grok Voice 3.0 WebSocket integration needs a visible start, a usable conversation, and a dependable stop. This guide focuses on browser session behavior; use the official reference for current event fields and connection parameters.
Treat a conversation as a state machine
A browser voice session has more states than connected or disconnected. Use explicit states such as idle, requesting permission, connecting, listening, responding, interrupted, stopping, and failed. The microphone indicator should reflect actual capture, not merely an open WebSocket.
Keep the provider protocol in a transport adapter. Your page should respond to application events rather than depending on every upstream event field.
type VoiceState =
| 'idle' | 'connecting' | 'listening'
| 'responding' | 'stopping' | 'failed';
function stopSession(socket: WebSocket, stream: MediaStream) {
stream.getTracks().forEach(track => track.stop());
socket.close(1000, 'User stopped the session');
}
This illustrates local cleanup. A complete implementation must also stop queued playback, release audio resources, and reconcile any server-side session.
Get credentials from your server
Follow xAI’s documented ephemeral-token flow for browser clients. The browser requests a short-lived session credential from your application after authentication and allowance checks. Never embed the permanent API key in a JavaScript bundle, source map, query string, or browser storage.
Issue a credential only when a user starts a session, not on every page view. If setup fails, show a clear retry action instead of silently opening repeated connections.
Separate audio capture and playback
Check the supported audio encoding, sample rate, and event format in the official Speech to Speech documentation. A MediaRecorder container is not automatically equivalent to the raw audio format an API expects.
When an interruption occurs, stop local queued output as well as updating the conversation state. Otherwise an assistant can appear to ignore the user even when the server accepted the interrupt.
Test the end of the session
Press stop during recording, while connecting, and halfway through playback. Navigate away, deny microphone permission, unplug an input device, and briefly lose the network. Confirm that no hidden recording track or abandoned billable connection remains.
The text-to-speech playground does not require microphone access. A future live-conversation UI should request it only when the user explicitly starts that workflow.
A Grok Voice 3.0 WebSocket session from start to finish
Map each stage to something the user can understand. A socket opening means the transport is available; it does not mean microphone permission was granted or that an assistant is already listening. Keep those milestones separate in your application, then expose a short status such as connecting or ready to speak. This avoids an active-looking interface that has never captured any input.
| Stage | Application responsibility | Useful visible feedback |
|---|---|---|
| Start requested | Check account access and session allowance | Preparing voice session |
| Permission requested | Handle microphone approval or refusal | Explain why the microphone is needed |
| Transport connecting | Authenticate and configure the session | Connecting, with a stop action |
| Listening | Capture input with the agreed audio settings | Clear microphone activity indicator |
| Responding | Decode and play current output | Speaking, with an interruption option |
| Stopping | End capture, playback, and transport resources | Ending the session |
| Ended or failed | Confirm local cleanup and reconcile server state | Ended, or a specific next step |
These are application design states, not a replacement event schema for the provider. The short TypeScript example above only illustrates stopping local tracks and a socket. It is not a complete transport implementation or a drop-in audio player.
Separate permission failures from connection failures
Test microphone permission before diagnosing audio generation. If permission is denied, show how to retry after changing the browser’s site setting. Reopening the socket will not grant microphone access. If no input device is available, tell the user to connect or select one rather than suggesting that the assistant is still preparing a response.
A user may allow the microphone while the device or browser pauses capture later. Check what happens when the tab goes into the background, the output device changes, or the operating system interrupts audio. Use the actual capture and playback status to update the interface. Do not leave a listening message visible merely because a conversation object remains in memory.
Keep the permission request tied to a deliberate start action. A documentation page and a narration preview do not need to open the microphone simply because a reader visits them. The homepage playground is a useful place to prepare a script without testing live capture.
Connect browser credentials to one deliberate start
Treat the short-lived credential as part of session setup, not as a public configuration value. Ask your server to authorize a new session, then establish the browser connection using the documented client authentication method. Follow the provider’s expiry rules rather than inventing a permanent lifetime for a temporary credential.
Double-clicking start should not create two hidden conversations. Disable or reconcile duplicate setup requests while one is pending, and release any abandoned resources if the user presses stop during setup. If setup times out, present one clear retry option. A retry should begin from a known state instead of leaving the old connection running alongside the new one.
Keep permanent credentials and sensitive upstream diagnostics on the server. The broader API integration guide covers account access, request lifecycle, and audio delivery. This session guide concentrates on what the browser must do while the conversation is active.
Make input and output audio agree on format
Document the capture format, conversion step, transport payload, decoder, and playback format separately. A file extension alone does not prove compatibility. A browser-produced recording can contain valid audio while still using a container or encoding that a particular streaming interface does not accept.
Use a short synthetic utterance to test the path before a long conversation. Listen for recognizable speech, truncation, unexpected speed, and distortion. Compare the declared settings with the bytes you actually send. If you change a sample rate or codec, repeat the full capture-to-playback test instead of assuming only one side of the connection changed.
For output, track which response owns each queued audio chunk. On interruption or session restart, discard output that belongs to an earlier response. Otherwise an old answer may play after the user has already supplied a correction. Keep ordering and playback cleanup within the audio layer so the visual status reflects what the listener is hearing.
Bound reconnection and avoid repeating actions
A temporary connection failure should lead to a bounded recovery attempt or a visible restart choice. Decide how many attempts your application will make, how long it will wait, and what state it will preserve. Show that the connection is recovering; do not keep the microphone looking ready when new input has nowhere to go.
Check the current provider documentation for supported resumption behavior. Do not assume a newly opened connection remembers earlier turns. If resumption is unavailable or fails, explain that the conversation must restart. Where you restore application context, avoid blindly replaying requests that could create a booking, send a message, or perform another external action.
Test a fictional interrupted task. Stop the network after a user requests an appointment but before the application confirms it. After recovery, the interface should distinguish unknown status from confirmed success. Reconcile the application record before retrying a side effect. Transport reconnection and business-action recovery are related, but they require different evidence.
Use a stop-and-recovery acceptance checklist
Run the following checks with synthetic speech and no real external actions: stop before permission is resolved; stop while connecting; interrupt the first answer; stop during playback; deny permission; remove the input device; navigate away; and briefly disconnect the network. For each case, record the final interface state and whether capture and playback ended.
Use browser developer tools to inspect your own application’s resource and event lifecycle. Save status categories and timing rather than full conversations or credentials. Repeat the checks on the browser and device combinations you intend to support, including a real phone if that is part of your release requirement. Desktop viewport resizing alone cannot verify mobile microphone behavior.
Questions about browser voice sessions
Does an open WebSocket prove the microphone works?
No. Transport, permission, input capture, and output playback are separate checks. Confirm a short spoken input reaches the application and produces an audible result before treating the complete audio path as ready.
Should every failure reconnect automatically?
No. A rejected permission request or missing account access needs a user action, not repeated connections. Use bounded recovery for the conditions it can actually fix. For a symptom-based sequence, use the voice troubleshooting guide.
Is this a live-conversation feature of the homepage?
This is an implementation guide for developers. The homepage offers short text-based voice previews. Preparing narration there does not require microphone permission and does not exercise a WebSocket conversation. Keep these workflows separate when planning your tests and explaining the product to users.