WebSocket Connection Flow
The connection process involves:- Fetching a temporary token from your server
- Connecting to AssemblyAI’s WebSocket endpoint
- Sending audio data when the connection opens
- Handling incoming transcript messages
- Properly closing the connection
Fetching the Temporary Token
Request token from your server
Before connecting to AssemblyAI, get a temporary token:Token validation: Check for the
public/index.js
error field in the response, verify that token exists before proceeding, and handle failures gracefully by alerting the user.Build the WebSocket URL
Construct the endpoint URL with query parameters:Query parameters explained:
public/index.js
sample_rate=16000: Must match your AudioContext sample rateformatted_finals=true: Returns formatted transcripts with punctuationtoken=${data.token}: Your temporary authentication token
The
sample_rate parameter must exactly match the sample rate you configured in your AudioContext (16000 Hz).WebSocket Event Handlers
onopen - Connection Established
When the WebSocket successfully connects, start sending audio:public/index.js
- Log connection success (line 2)
- Show the transcript message element (line 3)
- Start recording with callback (line 4)
- Check WebSocket is still open before sending (line 5)
- Send each audio chunk as it’s buffered (line 6)
onmessage - Receiving Transcripts
Handle incoming messages from AssemblyAI:public/index.js
- Parse JSON message from AssemblyAI (line 2)
- Check if it’s a “Turn” message (line 3)
- Extract turn order and transcript (line 4)
- Store in turns object keyed by order (line 5)
- Sort turns numerically (line 7-8)
- Join all turns into a single string (line 9-10)
- Update the UI with the complete transcript (line 12)
The Turn message type represents complete utterances. See Handling Transcripts for detailed message structure.
onerror - Connection Errors
Handle WebSocket errors:public/index.js
- Log error details for debugging
- Alert user about the problem
- Consider cleanup and reconnection logic
onclose - Connection Closed
Handle connection closure:public/index.js
- You explicitly close the connection
- The server closes the connection
- Network issues cause disconnection
Sending Audio Data
Audio chunks are sent as binary data:public/index.js
audioChunkis aUint8Arraycontaining 100ms of audio- WebSocket sends it as binary (not JSON)
- AssemblyAI processes it in real-time
Terminating the Session
Properly close the connection when stopping:public/index.js
- Send
Terminatemessage to notify AssemblyAI (line 2) - Close the WebSocket connection (line 3)
- Clear the reference (line 4)
Complete Connection Lifecycle
Here’s the full flow for starting and stopping:public/index.js
Connection State Management
Check the WebSocket state before operations:ws.readyState === WebSocket.OPEN before sending data.
Next Steps
With your WebSocket connected:- Learn about handling transcript messages
- Understand the Turn message format and ordering