Skip to main content

WebSocket connection guide

Use a WebSocket connection to access the Sambert real-time speech synthesis service. This topic covers the service endpoint, request headers, and interaction workflow.

The DashScope SDK currently supports only Java and Python. For other programming languages, use a WebSocket connection to communicate with the service. User guide: For model details and recommendations, see Speech synthesis.

Service endpoint

Sambert is available only in the Beijing region. The WebSocket service endpoint is: wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference Replace {WorkspaceId} with your actual workspace ID.
The URL is fixed and must use the wss:// protocol. Set the Authorization header as described in Request headers.
Alibaba Cloud Model Studio has released a workspace-specific domain for the China (Beijing) region. The new dedicated domain delivers superior performance and higher stability for inference requests. We recommend migrating from dashscope.aliyuncs.com to {WorkspaceId}.cn-beijing.maas.aliyuncs.com.Replace {WorkspaceId} with your actual Workspace ID. The existing domain remains fully functional.

Request headers

Include the following headers in the request:

Parameter

Type

Required

Description

Authorization

string

Yes

Authorization token in the format Bearer <your_api_key>. Replace <your_api_key> with your actual API key.

user-agent

string

No

Client identifier for server-side request tracking.

X-DashScope-WorkSpace

string

No

The workspace ID of Alibaba Cloud Model Studio.

X-DashScope-DataInspection

string

No

Controls data inspection. Data inspection is enabled by default when this parameter is not set. Set it to enable to explicitly turn on data inspection. Don't set this parameter unless necessary.

Authorization is verified during the WebSocket handshake. If the API key is invalid or missing, the handshake fails with an HTTP 401/403 error.

Interaction workflow

image
For details about client and server events, see Client events and Server-sent events. The client and server interact in the following sequence:
  1. Establish a connection: The client establishes a WebSocket connection with the server.
  2. Start a task: The client sends a run-task event to start a task. Sambert sends all text to synthesize in a single run-task event.
  3. Wait for confirmation: The client receives a task-started event from the server, which indicates that the task has started.
  4. Receive audio: The client receives an audio stream from the server over the binary channel. The client also receives result-generated events that carry additional information such as timestamps.
  5. Complete the task: The client receives a task-finished event from the server, which indicates that the task is complete.
  6. Close the connection: The client closes the WebSocket connection.
After task-finished, send another run-task with a new task_id on the same connection. Submit the complete text in each run-task.
Sambert supports output-only streaming (out), not bidirectional (duplex) streaming. All text to synthesize must be sent in a single run-task event. The continue-task and finish-task commands aren't supported.
For object pool configuration and a complete Java SDK concurrency example, see Speech synthesis best practices. When using the raw WebSocket protocol, reuse connections as described above.

Code examples

These examples use generic WebSocket libraries to send protocol events directly, with sambert-zhichu-v1. Obtain an API key, set the DASHSCOPE_API_KEY environment variable, and replace {WorkspaceId} with the workspace ID for the region. When switching regions, change both the endpoint and API key.
  • Go
  • C#
  • PHP
  • Node.js
go mod init tts-example
go get github.com/gorilla/websocket@v1.5.3 github.com/google/uuid@v1.6.0
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"

	"github.com/google/uuid"
	"github.com/gorilla/websocket"
)

const (
	wsURL      = "wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference" // WebSocket server address
	outputFile = "output.mp3"                                        // Output file path
)

func main() {
	// If you have not configured the API Key as an environment variable, replace the next line with: apiKey := "your_api_key". It is not recommended to hard-code the API Key directly in production code to reduce the risk of API Key leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")

	// Check and clear the output file
	if err := clearOutputFile(outputFile); err != nil {
		fmt.Println("Failed to clear output file:", err)
		return
	}

	// Connect to WebSocket service
	conn, err := connectWebSocket(apiKey)
	if err != nil {
		fmt.Println("Failed to connect to WebSocket:", err)
		return
	}
	defer closeConnection(conn)

	// Create a channel to receive task completion notifications
	done := make(chan struct{})

	// Start an asynchronous goroutine to receive messages
	go receiveMessage(conn, done)

	// Send run-task command
	if err := sendRunTaskMsg(conn); err != nil {
		fmt.Println("Failed to send run-task command:", err)
		return
	}

	// Wait for task completion or timeout
	select {
	case <-done:
		fmt.Println("Task ended")
	case <-time.After(5 * time.Minute):
		fmt.Println("Task timed out")
	}
}

// Define message struct
type Message struct {
	Header  Header  `json:"header"`
	Payload Payload `json:"payload"`
}

// Define header information
type Header struct {
	Action       string                 `json:"action,omitempty"`
	TaskID       string                 `json:"task_id"`
	Streaming    string                 `json:"streaming,omitempty"`
	Event        string                 `json:"event,omitempty"`
	ErrorCode    string                 `json:"error_code,omitempty"`
	ErrorMessage string                 `json:"error_message,omitempty"`
	Attributes   map[string]interface{} `json:"attributes"`
}

// Define payload information
type Payload struct {
	Model      string     `json:"model,omitempty"`
	TaskGroup  string     `json:"task_group,omitempty"`
	Task       string     `json:"task,omitempty"`
	Function   string     `json:"function,omitempty"`
	Input      Input      `json:"input,omitempty"`
	Parameters Parameters `json:"parameters,omitempty"`
	Output     Output     `json:"output,omitempty"`
	Usage      Usage      `json:"usage,omitempty"`
}

// Define input information
type Input struct {
	Text string `json:"text"`
}

// Define parameters information
type Parameters struct {
	TextType                string  `json:"text_type"`
	Format                  string  `json:"format"`
	SampleRate              int     `json:"sample_rate"`
	Volume                  int     `json:"volume"`
	Rate                    float64 `json:"rate"`
	Pitch                   float64 `json:"pitch"`
	WordTimestampEnabled    bool    `json:"word_timestamp_enabled"`
	PhonemeTimestampEnabled bool    `json:"phoneme_timestamp_enabled"`
}

// Define output information
type Output struct {
	Sentence Sentence `json:"sentence"`
}

// Define sentence information
type Sentence struct {
	BeginTime int    `json:"begin_time"`
	EndTime   int    `json:"end_time"`
	Words     []Word `json:"words"`
}

// Define word information
type Word struct {
	Text      string    `json:"text"`
	BeginTime int       `json:"begin_time"`
	EndTime   int       `json:"end_time"`
	Phonemes  []Phoneme `json:"phonemes"`
}

// Define phoneme information
type Phoneme struct {
	BeginTime int    `json:"begin_time"`
	EndTime   int    `json:"end_time"`
	Text      string `json:"text"`
	Tone      int    `json:"tone"`
}

// Define usage information
type Usage struct {
	Characters int `json:"characters"`
}

func receiveMessage(conn *websocket.Conn, done chan struct{}) {
	for {
		msgType, message, err := conn.ReadMessage()
		if err != nil {
			fmt.Println("Failed to parse server message:", err)
			close(done)
			break
		}

		if msgType == websocket.BinaryMessage {
			// Process binary audio stream
			if err := writeBinaryDataToFile(message, outputFile); err != nil {
				fmt.Println("Failed to write binary data:", err)
				close(done)
				break
			}
			fmt.Println("Audio segment written to local file")
		} else {
			// Process text message
			var msg Message
			if err := json.Unmarshal(message, &msg); err != nil {
				fmt.Println("Failed to parse event:", err)
				continue
			}
			if handleMessage(conn, msg, done) {
				break
			}
		}
	}
}

func handleMessage(conn *websocket.Conn, msg Message, done chan struct{}) bool {
	switch msg.Header.Event {
	case "task-started":
		fmt.Println("Task started")

	case "result-generated":
	// To retrieve additional messages, add the corresponding code here

	case "task-finished":
		fmt.Println("Task completed")
		close(done)
		return true

	case "task-failed":
		if msg.Header.ErrorMessage != "" {
			fmt.Printf("Task failed: %s\n", msg.Header.ErrorMessage)
		} else {
			fmt.Println("Task failed due to unknown reason")
		}
		close(done)
		return true

	default:
		fmt.Printf("Unexpected event: %v\n", msg)
		close(done)
	}

	return false
}

func sendRunTaskMsg(conn *websocket.Conn) error {
	runTaskMsg, err := generateRunTaskMsg()
	if err != nil {
		return err
	}
	if err := conn.WriteMessage(websocket.TextMessage, []byte(runTaskMsg)); err != nil {
		return err
	}
	return nil
}

func generateRunTaskMsg() (string, error) {
	runTaskMessage := Message{
		Header: Header{
			Action:    "run-task",
			TaskID:    uuid.New().String(),
			Streaming: "out",
		},
		Payload: Payload{
			Model:     "sambert-zhichu-v1",
			TaskGroup: "audio",
			Task:      "tts",
			Function:  "SpeechSynthesizer",
			Input: Input{
				Text: "The white sun descends behind the mountains, the Yellow River flows into the sea. To see a thousand li further, climb yet one more floor.",
			},
			Parameters: Parameters{
				TextType:                "PlainText",
				Format:                  "mp3",
				SampleRate:              16000,
				Volume:                  50,
				Rate:                    1.0,
				Pitch:                   1.0,
				WordTimestampEnabled:    true,
				PhonemeTimestampEnabled: true,
			},
		},
	}

	runTaskMsgJSON, err := json.Marshal(runTaskMessage)
	return string(runTaskMsgJSON), err
}

func connectWebSocket(apiKey string) (*websocket.Conn, error) {
	header := make(http.Header)
	header.Add("X-DashScope-DataInspection", "enable")
	header.Add("Authorization", fmt.Sprintf("bearer %s", apiKey))
	conn, _, err := websocket.DefaultDialer.Dial(wsURL, header)
	if err != nil {
		fmt.Println("Failed to connect to WebSocket:", err)
		return nil, err
	}
	return conn, nil
}

func writeBinaryDataToFile(data []byte, filePath string) error {
	file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer file.Close()
	_, err = file.Write(data)
	return err
}

func closeConnection(conn *websocket.Conn) {
	if conn != nil {
		conn.Close()
	}
}

func clearOutputFile(filePath string) error {
	file, err := os.OpenFile(filePath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	file.Close()
	return nil
}

Available SDKs