Learn how to send Deepgram a CloseStream message, which closes the websocket stream.

Streaming

In real-time audio processing, there are scenarios where you may need to force the server to close. Deepgram supports a CloseStream message to handle such situations. This message will send a shutdown command to the server instructing it to finish processing any cached data, send the response to the client, send a summary metadata object, and then terminate the WebSocket connection.

What is the CloseStream Message

The CloseStream message is a JSON command that you send to the Deepgram server, instructing it close the connection. This is particularly useful in scenarios where you need to immediately shutdown the websocket connection and process and return all data to the client.

Sending CloseStream

To send the CloseStream message, you need to send the following JSON message to the server:

JSON
1{
2 "type": "CloseStream"
3}

CloseStream Confirmation

Upon receiving the CloseStream message, the server will process all remaining audio data and return the following:

JSON
1{
2 "type": "Metadata",
3 "transaction_key": "deprecated",
4 "request_id": "8c8ebea9-dbec-45fa-a035-e4632cb05b5f",
5 "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
6 "created": "2024-08-29T22:37:55.202Z",
7 "duration": 0.0,
8 "channels": 0
9}

Language-Specific Implementations

1const WebSocket = require("ws");
2
3// Assuming 'headers' is already defined for authorization
4const ws = new WebSocket("wss://api.deepgram.com/v1/listen", { headers });
5
6ws.on('open', function open() {
7 // Construct CloseStream message
8 const closeStreamMsg = JSON.stringify({ type: "CloseStream" });
9
10 // Send CloseStream message
11 ws.send(closeStreamMsg);
12});

Conclusion

In summary, when dealing with real-time audio processing, there are situations where it may be necessary to forcibly close the server connection. Deepgram provides the CloseStream message to facilitate this process. By sending this message, the server is instructed to complete processing any buffered data, return the final response along with summary metadata, and then gracefully terminate the WebSocket connection. This ensures a controlled shutdown, preserving the integrity of the data and the overall process.


Built with