Streaming TTS vs. Regular TTS: WebSocket Frames, Signed URLs, and Write Streams, End to End
What's the difference between streaming TTS and regular TTS? One document teaches you!
Using Tencent Cloud's WebSocket streaming TTS test code as an example, this document explains the difference between regular TTS and streaming TTS, the complete execution flow of streaming TTS, and concepts that are easy to confuse while learning.
1. What is TTS
TTS is short for Text to Speech, meaning "text to speech".
Regular TTS basic process:
Input complete text
↓
Submit to TTS service
↓
Wait for all audio synthesis to complete
↓
Receive complete audio
↓
Save or play
Streaming TTS basic process:
Input the first segment of text
↓
Establish a WebSocket long connection
↓
Continue sending text
↓
Receive audio chunks at the same time
↓
Chunks are continuously written to the same audio file
Main advantage of streaming TTS: the first audio segment can arrive earlier, suitable for voice assistants, real-time conversations, LLM voice broadcast, and similar scenarios.
2. Differences between regular TTS and streaming TTS
| Regular TTS | Streaming TTS |
|---|---|
| Uses HTTP requests | Uses WebSocket long connection |
| Submits complete text | Can send text in segments |
| Waits for complete audio | Continuously receives audio chunks |
| Audio is usually returned as a Base64 string | Audio is transmitted directly via binary frames |
| Writes a complete file at once | Continuously appends through a write stream |
| Simple to implement | Requires handling the complete event flow |
A regular TTS response usually looks like:
{
"Audio": "SUQzBAAAAAAAI1RTU0U..."
}
Because JSON can only express text, audio is converted into a Base64 string. After receiving the result, you need to decode it:
const audioBuffer = Buffer.from(data.Audio, "base64");
Streaming TTS uses WebSocket binary frames to transmit audio; what is received is already raw audio bytes:
FF F3 48 C4 ...
So there is no need for Base64 decoding; write directly to a file:
writeStream.write(data);
3. Complete flow of streaming TTS
Read environment variables and keys
↓
Generate sessionId
↓
Sort parameters and compute signature
↓
Build WSS URL
↓
Establish WebSocket connection
↓
Create audio file write stream
↓
Server sends text frame: ready=1
↓
Client sends ACTION_SYNTHESIS text frame
↓
Server returns binary audio frame
↓
Client continuously writes audio frames to file
↓
After all text is sent, send ACTION_COMPLETE
↓
Server sends text frame: final=1
↓
End file write stream
↓
Close WebSocket
4. WebSocket text frames and binary frames
WebSocket can send two main types of messages:
Text frames
Binary frames
In Node.js ws library, the callback for the message event is usually written as:
ws.on("message", (data, isBinary) => {
// data: message content
// isBinary: whether it is a binary frame
});
data and isBinary are passed in by the ws library when a message is received; they are not generated by your own function.
4.1 Text frames
Tencent Cloud streaming TTS uses text frames to return control information, for example:
{"ready": 1}
In Node.js, data is usually a Buffer. You need to convert it to a UTF-8 string and then parse the JSON:
const text = data.toString();
const msg = JSON.parse(text);
Complete process:
Network bytes
↓
Buffer
↓ data.toString()
JSON string
↓ JSON.parse(...)
JavaScript object
4.2 Binary frames
Binary frames returned by streaming TTS represent raw audio bytes. MP3 data may look like:
FF F3 48 C4 ...
Audio binary data cannot be treated as ordinary text according to UTF-8, and you should not perform Base64 decoding. Write it directly to the file stream:
writeStream.write(data);
4.3 Branch handling by frame type
ws.on("message", async (data, isBinary) => {
if (isBinary) {
// binary frame: audio
writeStream.write(data);
totalBytes += data.length;
return;
}
// text frame: JSON control message
try {
const msg = JSON.parse(data.toString());
if (msg.ready === 1) {
// Server is ready, may send text
}
if (msg.final === 1) {
// Server has completed all synthesis
}
} catch (error) {
console.error("JSON parse failed:", error.message);
}
});
Here, return only ends the current message callback; it does not close WebSocket or prevent subsequent messages from arriving.
5. Building the WSS URL
The WebSocket URL must be built from parameters, time, session ID, and signature provided by Tencent Cloud.
function buildWsUrl() {
const now = Math.floor(Date.now() / 1000);
const sessionId =
`session_${now}_${Math.random().toString(36).slice(2)}`;
const params = {
Action: "TextToStreamAudioWSv2",
AppId: parseInt(APP_ID),
Codec: "mp3",
Expired: now + 3600,
SampleRate: 16000,
SecretId: SECRET_ID,
SessionId: sessionId,
Speed: 0,
Timestamp: now,
VoiceType: VOICE_TYPE,
Volume: 5
};
const sortedKeys = Object.keys(params).sort();
const signStr = sortedKeys
.map((key) => `${key}=${params[key]}`)
.join("&");
const rawStr =
`GETtts.cloud.tencent.com/stream_wsv2?${signStr}`;
const signature = crypto
.createHmac("sha1", SECRET_KEY)
.update(rawStr)
.digest("base64");
const searchParams = new URLSearchParams({
...params,
Signature: signature
});
return {
sessionId,
url:
`wss://tts.cloud.tencent.com/stream_wsv2?` +
searchParams.toString()
};
}
5.1 Key parameters
| Parameter | Meaning |
|---|---|
Action |
The streaming TTS interface being called |
AppId |
Tencent Cloud application ID |
Codec |
Audio encoding format, e.g. MP3 |
Expired |
Signature expiration time |
SampleRate |
Audio sample rate |
SecretId |
Tencent Cloud SecretId |
SessionId |
Current synthesis session ID |
Speed |
Speech speed |
Timestamp |
Current time |
VoiceType |
Voice timbre |
Volume |
Volume |
5.2 Why sort?
Tencent Cloud requires the signature parameters to be concatenated in alphabetical order of field names. Therefore:
const sortedKeys = Object.keys(params).sort();
The concatenated content is similar to:
Action=TextToStreamAudioWSv2&AppId=123456&Codec=mp3&...
Then add the request method, domain name, and path:
GETtts.cloud.tencent.com/stream_wsv2?Action=...
5.3 Why compute a signature?
SecretId identifies the caller; SecretKey proves the caller's identity.
The signature calculation process can be understood as:
Content to sign
+
SecretKey
↓
HMAC-SHA1
↓
Base64 encoding
↓
Signature
SecretKey is only kept locally and is not put directly into the connection URL.
5.4 Case-convention confusion
URL query parameters use:
SessionId: sessionId
WebSocket messages use:
session_id: sessionId
The field names are different, but the values they hold must be identical.
6. Sending text messages
The server sends:
{"ready": 1}
This means the connection is ready and the client can start sending text to be synthesized.
The field structure of a text message is:
const frame = {
session_id: sessionId,
message_id: `msg_${i}`,
action: "ACTION_SYNTHESIS",
data: TEXTS[i]
};
ws.send(JSON.stringify(frame));
| Field | Fixed? | Meaning |
|---|---|---|
session_id |
Field name fixed | Current session ID |
message_id |
Field name fixed | Current message number |
action |
Field name and value fixed | Means synthesize a segment of text |
data |
Field name fixed | The text to be converted to speech |
Among those:
- The value of
session_idmust match theSessionIdin the signed URL. message_idvalues may be generated by you, but should not repeat within the same session.actionshould use the protocol-specifiedACTION_SYNTHESIS.datacan be any valid text fragment.
Example:
{
"session_id": "session_1764412345_k3j9x2a",
"message_id": "msg_0",
"action": "ACTION_SYNTHESIS",
"data": "Hello, I am a voice assistant"
}
7. Completing text sending
After all text is sent, a completion message must be sent:
ws.send(JSON.stringify({
session_id: sessionId,
action: "ACTION_COMPLETE"
}));
This message means:
All text for this session has been sent; the server may finish synthesis.
Common client actions:
| action | Fields | Meaning |
|---|---|---|
ACTION_SYNTHESIS |
session_id, message_id, action, data |
Synthesize a segment of text |
ACTION_COMPLETE |
session_id, action |
All text has been sent |
8. Why do we need the sent state?
The example code has:
let sent = false;
if (msg.ready === 1 && !sent) {
sent = true;
await sendTexts(ws, sessionId);
}
sent does not mean "after sending one text, no more text can be sent"; it means:
Whether this text-sending flow has been started.
After sent is set to true, the loop inside sendTexts() still sends all text:
msg_0
msg_1
msg_2
msg_3
msg_4
ACTION_COMPLETE
Its purpose is to prevent a second sendTexts() from being started when the server re-sends ready=1.
It must be set before await sendTexts():
sent = true;
await sendTexts(ws, sessionId);
Because sendTexts() contains a wait operation. If another ready=1 arrives during the wait and sent has not been set, text may be sent repeatedly.
For clarity, you can name it this way:
let textStreamStarted = false;
if (msg.ready === 1 && !textStreamStarted) {
textStreamStarted = true;
await sendTexts(ws, sessionId);
}
9. Writing the audio file
Regular TTS can write the complete audio at once:
fs.writeFile(outputPath, audioBuffer, callback);
Streaming TTS cannot know the complete audio size in advance, so it uses a write stream:
const writeStream = fs.createWriteStream(OUTPUT_FILE, {
flags: "w"
});
Each subsequent audio chunk is appended to the same file:
if (isBinary) {
writeStream.write(data);
totalBytes += data.length;
}
Audio transmission process:
audio chunk 1 ┐
audio chunk 2 ├──→ writeStream ──→ output3.mp3
audio chunk 3 ┘
flags: "w" means that if the file already exists, its contents are cleared. So every run overwrites the old file with the same name.
After synthesis is complete, the file stream must be ended:
writeStream.end(() => {
console.log(`Audio saved, total ${totalBytes} bytes`);
});
end() waits for the remaining buffered data to be actually written to the file.
10. Server message handling
The example code handles the following text messages:
{"ready": 1}
Means text can start being sent.
{"final": 1}
Means all audio synthesis is finished.
{
"code": 10001,
"message": "Error reason"
}
Means the server returned an error.
The handling logic can be simplified to:
if (msg.ready === 1 && !textStreamStarted) {
textStreamStarted = true;
await sendTexts(ws, sessionId);
}
if (msg.code !== undefined && Number(msg.code) !== 0) {
console.error(msg.message);
closeAll();
} else if (msg.final === 1) {
closeAll();
}
11. Closing flow
You can handle closing uniformly with one function:
let closed = false;
function closeAll() {
if (closed) return;
closed = true;
writeStream.end(() => {
console.log(`Audio saved to ${OUTPUT_FILE}`);
});
if (ws.readyState < WebSocket.CLOSING) {
ws.close();
}
}
closed prevents multiple events from repeatedly executing the closing flow.
WebSocket readyState states:
| Value | Constant | Meaning |
|---|---|---|
| 0 | CONNECTING |
Connecting |
| 1 | OPEN |
Connected |
| 2 | CLOSING |
Closing |
| 3 | CLOSED |
Closed |
You need to listen for WebSocket errors:
ws.on("error", (error) => {
console.error("WebSocket error:", error.message);
closeAll();
});
You also need to listen for connection close:
ws.on("close", (code, reason) => {
console.log(`WebSocket closed: ${code}`);
closeAll();
});
12. Complete event execution order
1. Load dotenv and node_modules dependencies
2. Read SecretId, SecretKey, AppId
3. Generate timestamp and unique sessionId
4. Prepare parameters and compute signature
5. Create WebSocket and file write stream
6. Register open, message, error, close events
7. Connection succeeds, open fires
8. Server returns ready=1
9. Client sends the first text segment
10. Server returns binary audio chunks
11. Client writes audio chunks to file
12. Client continues sending subsequent text
13. Client sends ACTION_COMPLETE
14. Server returns final=1
15. Client ends file stream
16. Client closes WebSocket
13. Why event listeners can call functions automatically
When registering an event:
ws.on("message", handler);
This only gives the handler function to ws to store; it does not call it immediately.
When the server sends a message, ws internally does something like:
handler(data, isBinary);
ws specifies that the callback parameters for the message event are in this order:
first parameter: message content data
second parameter: whether it is binary isBinary
Parameter names can be changed:
ws.on("message", (messageData, binaryFlag) => {
if (binaryFlag) {
writeStream.write(messageData);
}
});
What matters is parameter position, not parameter name.
14. Common misconceptions
Misconception 1: Streaming audio needs Base64 decoding
Wrong. WebSocket binary frames are already raw audio bytes; they should be written directly to a file.
Misconception 2: node:crypto needs extra installation
Wrong. node:crypto and node:fs are built-in Node.js modules. What needs to be installed are ws and dotenv.
Misconception 3: The WSS URL is returned by the server
Wrong. The client generates the sessionId locally, computes the signature, and builds the WSS URL.
Misconception 4: Each audio chunk should be saved as a separate file
Wrong. All audio chunks belong to the same audio stream and should be appended to the same file.
Misconception 5: After sent=true, only one text can be sent
Wrong. sent only controls whether sendTexts() is started; the loop still sends all text.
Misconception 6: return closes WebSocket
Wrong. return only ends the current message callback. The next message will still trigger the callback.
Misconception 7: The text frame's data is already a JSON object
Wrong. data is usually a Buffer; first convert it with toString(), then use JSON.parse().
15. Recommended learning sequence
Phase 1: Regular TTS
- Understand request and response.
- Modify voice, speed, and volume.
- Understand Base64 audio strings.
- Save complete audio as MP3.
Phase 2: Streaming TTS
- Understand WebSocket long connections.
- Understand text frames and binary frames.
- Understand
ready,ACTION_SYNTHESIS,ACTION_COMPLETE,final. - Understand audio write streams.
Phase 3: Statistics and optimization
In the code, record:
Request start time
Time of first audio chunk received
Time when all synthesis completes
Number of audio chunks
Final file size
This allows comparison of first-packet latency and total synthesis time.
Phase 4: Integrating an LLM
Target flow:
LLM streams text output
↓
Split by sentence or phrase
↓
Send each segment to streaming TTS
↓
Continuously receive audio
↓
Play or forward to browser
Text fragments should not be too short or too long. Too short may cause unnatural pauses; too long increases the waiting time for the first audio segment.
16. Security and engineering notes
SecretKeymust only be stored on the server; never expose it to the browser.- Do not use
console.logto output the full secret key. - Need to handle WebSocket errors, timeouts, and disconnections.
- Need to handle file write errors.
- Should properly end the file stream so the last audio segment is written to disk.
- When doing multiple synthesis jobs, control concurrency.
- When the user interrupts speech, stop current synthesis and discard unplayed audio.
- In real development, always follow the official protocol documentation of the vendor's current version.
17. One-sentence summary
Regular TTS is "complete text in, complete audio out"; streaming TTS is "continuously send text over WebSocket, continuously receive audio binary chunks, and write the chunks into the same audio stream".