All Products
Search
Document Center

Alibaba Cloud Model Studio:SSML and LaTeX

Last Updated:Nov 30, 2026

Use SSML to control voice characteristics such as speech rate, pitch, and volume, and use LaTeX to read Chinese mathematical formulas aloud. This article introduces the supported scope, invocation examples, and tag and symbol references.

Feature overview

SSML is an XML-based speech synthesis markup language that can set voice characteristics such as timbre, speaking rate, pitch, and volume, control pauses, specify pronunciation and reading styles, and add background music and sound effects. The LaTeX formula reading feature of CosyVoice converts mathematical formulas in text into Chinese speech.

These two features can be used for audiobooks, customer service information announcements, multilingual pronunciation, and online education. The applicable models, voices, and interfaces for each feature are described below. For model selection, see Speech synthesis.

Limits

SSML

  • Supported models: qwen-audio-3.1-tts-plus, qwen-audio-3.1-tts-flash, qwen-audio-3.0-tts-flash, qwen-audio-3.0-tts-plus, cosyvoice-v3.5-flash, cosyvoice-v3.5-plus, cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2

  • Voices: Only cloned voices and the system voices marked as supporting SSML in the Qwen-Audio-TTS voice list and CosyVoice voice list are available.

  • Interfaces:
    • Java SDK (v2.20.3 or later): supports non-streaming calls and one-way streaming calls
    • Python SDK (v2.0.1 or later): supports non-streaming calls and one-way streaming calls
    • WebSocket API: you must set the enable_ssml parameter to true, and the continue-task event can be sent only once

LaTeX

  • Supported models: cosyvoice-v3.5-plus, cosyvoice-v3.5-flash, cosyvoice-v3-plus, cosyvoice-v3-flash, cosyvoice-v2

  • Language: Only Chinese is supported.

  • Content: Formulas must be within the supported tags and symbols. Markdown math formula code blocks (for example, code blocks labeled math) are not supported. Put only formulas inside the delimiters; mixing in non-formula text may cause inaccurate reading.

Usage

SSML

When using SSML, follow these rules:

  • All text must be placed in <speak></speak>. Multiple <speak> tags can be used side by side; nesting is not supported.
  • Special XML characters inside tags must be escaped: " → &quot;, ' → &apos;, & → &amp;, < → &lt;, > → &gt;.

QuickStart

The following example shows how to use SSML to control the speaking rate for speech synthesis. Before running it, complete the following preparations:

  1. Obtain and configure an API Key
  2. Install the DashScope SDK (Python 2.0.1 or later, Java 2.20.3 or later). For details, see Install the SDK.

Importantcosyvoice-v3.5-plus and cosyvoice-v3.5-flash do not provide system voices. To use these two models in the SSML examples in this section, you must first create a cloned voice through voice cloning.

Java SDK

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.utils.Constants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * SSML feature description:
 *     1. Only non-streaming calls and unidirectional streaming calls support the SSML feature
 * Use an SSML-compatible cloned or preset voice (such as longanyang for cosyvoice-v3-flash). See this page for supported models.
 */
public class Main {
    private static String model = "cosyvoice-v3-flash";
    private static String voice = "longanyang";

    public static void main(String[] args) {
        // Singapore region URL. Replace WorkspaceId with your actual workspace ID. The URL varies by region.
        Constants.baseWebsocketApiUrl = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference";
        streamAudioDataToSpeaker();
        System.exit(0);
    }

    public static void streamAudioDataToSpeaker() {
        SpeechSynthesisParam param =
                SpeechSynthesisParam.builder()
                        // The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
                        // If you have not configured an environment variable, replace the following line with your Model Studio API Key: .apiKey("sk-xxx")
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(model)
                        .voice(voice)
                        .build();

        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
        ByteBuffer audio = null;
        try {
            // Non-streaming call, blocks until audio is returned
            // Special characters need to be escaped
            audio = synthesizer.call("<speak rate=\"2\">I am speaking faster than usual.</speak>");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // Close the WebSocket connection when the task ends
            synthesizer.getDuplexApi().close(1000, "bye");
        }
        if (audio != null) {
            // Save audio data to local file "output.mp3"
            File file = new File("output.mp3");
            try (FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(audio.array());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        // The first text transmission requires establishing a WebSocket connection, so the first packet latency includes the connection setup time
        System.out.println(
                "[Metric] requestId: "
                        + synthesizer.getLastRequestId()
                        + ", first packet latency (ms): "
                        + synthesizer.getFirstPackageDelay());
    }
}
import com.alibaba.dashscope.audio.tts.SpeechSynthesisResult;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisAudioFormat;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.utils.Constants;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * SSML feature description:
 *     1. Only non-streaming calls and unidirectional streaming calls support the SSML feature
 * Use an SSML-compatible cloned or preset voice (such as longanyang for cosyvoice-v3-flash). See this page for supported models.
 */
public class Main {
    private static String model = "cosyvoice-v3-flash";
    private static String voice = "longanyang";

    public static void main(String[] args) {
        // Singapore region URL. Replace WorkspaceId with your actual workspace ID. The URL varies by region.
        Constants.baseWebsocketApiUrl = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference";
        streamAudioDataToSpeaker();
        System.out.println("Audio has been saved to the output.mp3 file");
        System.exit(0);
    }

    public static void streamAudioDataToSpeaker() {
        CountDownLatch latch = new CountDownLatch(1);
        final FileOutputStream[] fileOutputStream = new FileOutputStream[1];

        try {
            fileOutputStream[0] = new FileOutputStream("output.mp3");
        } catch (IOException e) {
            System.err.println("Failed to create output file: " + e.getMessage());
            return;
        }

        // Implement the ResultCallback interface
        ResultCallback<SpeechSynthesisResult> callback = new ResultCallback<SpeechSynthesisResult>() {
            @Override
            public void onEvent(SpeechSynthesisResult result) {
                if (result.getAudioFrame() != null) {
                    // Write audio data to local file
                    try {
                        byte[] audioData = result.getAudioFrame().array();
                        fileOutputStream[0].write(audioData);
                        fileOutputStream[0].flush();
                    } catch (IOException e) {
                        System.err.println("Failed to write audio data: " + e.getMessage());
                    }
                }
            }

            @Override
            public void onComplete() {
                System.out.println("Received Complete, speech synthesis finished");
                closeFileOutputStream(fileOutputStream[0]);
                latch.countDown();
            }

            @Override
            public void onError(Exception e) {
                System.out.println("An error occurred: " + e.toString());
                closeFileOutputStream(fileOutputStream[0]);
                latch.countDown();
            }
        };

        SpeechSynthesisParam param =
                SpeechSynthesisParam.builder()
                        // The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
                        // If you have not configured an environment variable, replace the following line with your Model Studio API Key: .apiKey("sk-xxx")
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(model)
                        .voice(voice)
                        .format(SpeechSynthesisAudioFormat.MP3_22050HZ_MONO_256KBPS)
                        .build();

        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, callback);

        try {
            // Unidirectional streaming call, returns null immediately (actual results are delivered asynchronously via the callback interface), retrieve binary audio in real time from the onEvent method of the callback interface
            // Special characters need to be escaped
            synthesizer.call("<speak rate=\"2\">I am speaking faster than usual.</speak>");
            // Wait for synthesis to complete
            latch.await();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // Close the WebSocket connection after the task ends
            try {
                synthesizer.getDuplexApi().close(1000, "bye");
            } catch (Exception e) {
                System.err.println("Failed to close WebSocket connection: " + e.getMessage());
            }

            // Ensure the file stream is closed
            closeFileOutputStream(fileOutputStream[0]);
        }

        // The first text transmission requires establishing a WebSocket connection, so the first packet latency includes the connection setup time
        System.out.println(
                "[Metric] requestId: "
                        + synthesizer.getLastRequestId()
                        + ", first packet latency (ms): "
                        + synthesizer.getFirstPackageDelay());
    }

    private static void closeFileOutputStream(FileOutputStream fileOutputStream) {
        try {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            System.err.println("Failed to close file stream: " + e.getMessage());
        }
    }
}

Python SDK

# coding=utf-8
# SSML feature description:
#     1. Only non-streaming calls and unidirectional streaming calls support the SSML feature
# Use an SSML-compatible cloned or preset voice (such as longanyang for cosyvoice-v3-flash). See this page for supported models.

import os

import dashscope

# The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured an environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
# The following is the configuration for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
client = dashscope.Client(
    api_key=os.environ.get('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

# Model
model = "cosyvoice-v3-flash"
# Voice
voice = "longanyang"

# Non-streaming call, blocks until the audio is returned
# Special characters need to be escaped
audio = client.audio.tts.synthesize(
    "<speak rate=\"2\">I am speaking faster than usual.</speak>",
    model=model,
    voice=voice,
    enable_ssml=True)

# Save the audio to a local file
with open('output.mp3', 'wb') as f:
    f.write(audio)
# coding=utf-8
# SSML feature description:
#     1. Only non-streaming calls and unidirectional streaming calls support the SSML feature
# Use an SSML-compatible cloned or preset voice (such as longanyang for cosyvoice-v3-flash). See this page for supported models.

import os
from datetime import datetime

import dashscope

def get_timestamp():
    now = datetime.now()
    formatted_timestamp = now.strftime("[%Y-%m-%d %H:%M:%S.%f]")
    return formatted_timestamp

# The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured an environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
# The following is the configuration for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
client = dashscope.Client(
    api_key=os.environ.get('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

# Model
model = "cosyvoice-v3-flash"
# Voice
voice = "longanyang"

# Unidirectional streaming call, send the text for synthesis and retrieve binary audio chunks in real time
# Special characters need to be escaped
with open("output.mp3", "wb") as f:
    for chunk in client.audio.tts.stream(
            "<speak rate=\"2\">I am speaking faster than usual.</speak>",
            model=model,
            voice=voice,
            enable_ssml=True):
        print(get_timestamp() + " Binary audio length: " + str(len(chunk)))
        # Write the audio data to file
        f.write(chunk)
print("Speech synthesis completed, all results have been received: " + get_timestamp())

WebSocket API

Java

For Java development, we recommend using the Java DashScope SDK. For details, see Java SDK.

The following is a Java WebSocket invocation example. Before running the example, make sure the following dependencies are imported:

  • Java-WebSocket
  • jackson-databind

We recommend using Maven or Gradle to manage dependencies. The configuration is as follows:

<dependencies>
    <!-- WebSocket Client -->
    <dependency>
        <groupId>org.java-websocket</groupId>
        <artifactId>Java-WebSocket</artifactId>
        <version>1.5.3</version>
    </dependency>

    <!-- JSON Processing -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.0</version>
    </dependency>
</dependencies>
// Other code omitted
dependencies {
  // WebSocket Client
  implementation 'org.java-websocket:Java-WebSocket:1.5.3'
  // JSON Processing
  implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
}
// Other code omitted

The Java code is as follows:

import com.fasterxml.jackson.databind.ObjectMapper;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.*;

/**
 * SSML feature description:
 *     1. When sending the run-task command, set the enable_ssml parameter to true to enable SSML support
 *     2. Send text containing SSML via the continue-task command, and only one continue-task command is allowed
 * Use an SSML-compatible cloned or preset voice (such as longanyang for cosyvoice-v3-flash). See this page for supported models.
 */
public class TTSWebSocketClient extends WebSocketClient {
    private final String taskId = UUID.randomUUID().toString();
    private final String outputFile = "output_" + System.currentTimeMillis() + ".mp3";
    private boolean taskFinished = false;

    public TTSWebSocketClient(URI serverUri, Map<String, String> headers) {
        super(serverUri, headers);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        System.out.println("Connection established");

        // Send run-task command
        // If enable_ssml is set to true, only one continue-task command is allowed; otherwise the error "Text request limit violated, expected 1." will be returned
        String runTaskCommand = "{ \"header\": { \"action\": \"run-task\", \"task_id\": \"" + taskId + "\", \"streaming\": \"duplex\" }, \"payload\": { \"task_group\": \"audio\", \"task\": \"tts\", \"function\": \"SpeechSynthesizer\", \"model\": \"cosyvoice-v3-flash\", \"parameters\": { \"text_type\": \"PlainText\", \"voice\": \"longanyang\", \"format\": \"mp3\", \"sample_rate\": 22050, \"volume\": 50, \"rate\": 1, \"pitch\": 1, \"enable_ssml\": true }, \"input\": {} }}";
        send(runTaskCommand);
    }

    @Override
    public void onMessage(String message) {
        System.out.println("Received message from server: " + message);
        try {
            // Parse JSON message
            Map<String, Object> messageMap = new ObjectMapper().readValue(message, Map.class);

            if (messageMap.containsKey("header")) {
                Map<String, Object> header = (Map<String, Object>) messageMap.get("header");

                if (header.containsKey("event")) {
                    String event = (String) header.get("event");

                    if ("task-started".equals(event)) {
                        System.out.println("Received task-started event from server");

                        // Send continue-task command. When using SSML, this command can only be sent once
                        // Special characters need to be escaped
                        sendContinueTask("<speak rate=\\\"2\\\">I am speaking faster than usual.</speak>");

                        // Send finish-task command
                        sendFinishTask();
                    } else if ("task-finished".equals(event)) {
                        System.out.println("Received task-finished event from server");
                        taskFinished = true;
                        closeConnection();
                    } else if ("task-failed".equals(event)) {
                        System.out.println("Task failed: " + message);
                        closeConnection();
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
        }
    }

    @Override
    public void onMessage(ByteBuffer message) {
        System.out.println("Received binary audio data, size: " + message.remaining());

        try (FileOutputStream fos = new FileOutputStream(outputFile, true)) {
            byte[] buffer = new byte[message.remaining()];
            message.get(buffer);
            fos.write(buffer);
            System.out.println("Audio data written to local file " + outputFile);
        } catch (IOException e) {
            System.err.println("Failed to write audio data to local file: " + e.getMessage());
        }
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("Connection closed: " + reason + " (" + code + ")");
    }

    @Override
    public void onError(Exception ex) {
        System.err.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    }

    private void sendContinueTask(String text) {
        String command = "{ \"header\": { \"action\": \"continue-task\", \"task_id\": \"" + taskId + "\", \"streaming\": \"duplex\" }, \"payload\": { \"input\": { \"text\": \"" + text + "\" } }}";
        send(command);
    }

    private void sendFinishTask() {
        String command = "{ \"header\": { \"action\": \"finish-task\", \"task_id\": \"" + taskId + "\", \"streaming\": \"duplex\" }, \"payload\": { \"input\": {} }}";
        send(command);
    }

    private void closeConnection() {
        if (!isClosed()) {
            close();
        }
    }

    public static void main(String[] args) {
        try {
            // The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
            // If you have not configured an environment variable, replace the following line with your Model Studio API Key: String apiKey = "sk-xxx"
            String apiKey = System.getenv("DASHSCOPE_API_KEY");
            if (apiKey == null || apiKey.isEmpty()) {
                System.err.println("Please set the DASHSCOPE_API_KEY environment variable");
                return;
            }

            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "bearer " + apiKey);
            // Singapore region URL. Replace WorkspaceId with your actual workspace ID. The URL varies by region.
            TTSWebSocketClient client = new TTSWebSocketClient(new URI("wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference/"), headers);

            client.connect();

            while (!client.isClosed() && !client.taskFinished) {
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            System.err.println("Failed to connect to WebSocket service: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Python

For Python development, we recommend using the Python DashScope SDK. For details, see Python SDK.

The following is a Python WebSocket invocation example. Before running the example, make sure to import the dependencies as follows:

pip uninstall websocket-client
pip uninstall websocket
pip install websocket-client

ImportantThe Python file that runs the sample code must not be named websocket.py; otherwise, an error occurs (AttributeError: module 'websocket' has no attribute 'WebSocketApp'. Did you mean: 'WebSocket'?).

# SSML feature description:
#     1. When sending the run-task command, set the enable_ssml parameter to true to enable SSML support
#     2. Send text containing SSML via the continue-task command, and only one continue-task command is allowed
# Use an SSML-compatible cloned or preset voice (such as longanyang for cosyvoice-v3-flash). See this page for supported models.

import websocket
import json
import uuid
import os
import time

class TTSClient:
    def __init__(self, api_key, uri):
        """
    Initialize a TTSClient instance

    Parameters:
        api_key (str): API Key for authentication
        uri (str): WebSocket service address
    """
        self.api_key = api_key  # Replace with your API Key
        self.uri = uri  # Replace with your WebSocket address
        self.task_id = str(uuid.uuid4())  # Generate a unique task ID
        self.output_file = f"output_{int(time.time())}.mp3"  # Output audio file path
        self.ws = None  # WebSocketApp instance
        self.task_started = False  # Whether task-started has been received
        self.task_finished = False  # Whether task-finished / task-failed has been received

    def on_open(self, ws):
        """
    Callback when WebSocket connection is established
    Sends run-task command to start the speech synthesis task
    """
        print("WebSocket connected")

        # Construct run-task command
        run_task_cmd = {
            "header": {
                "action": "run-task",
                "task_id": self.task_id,
                "streaming": "duplex"
            },
            "payload": {
                "task_group": "audio",
                "task": "tts",
                "function": "SpeechSynthesizer",
                "model": "cosyvoice-v3-flash",
                "parameters": {
                    "text_type": "PlainText",
                    "voice": "longanyang",
                    "format": "mp3",
                    "sample_rate": 22050,
                    "volume": 50,
                    "rate": 1,
                    "pitch": 1,
                    # If enable_ssml is set to True, only one continue-task command is allowed; otherwise the error "Text request limit violated, expected 1." will be returned
                    "enable_ssml": True
                },
                "input": {}
            }
        }

        # Send run-task command
        ws.send(json.dumps(run_task_cmd))
        print("run-task command sent")

    def on_message(self, ws, message):
        """
    Callback when a message is received
    Handles text and binary messages separately
    """
        if isinstance(message, str):
            # Process JSON text messages
            try:
                msg_json = json.loads(message)
                print(f"Received JSON message: {msg_json}")

                if "header" in msg_json:
                    header = msg_json["header"]

                    if "event" in header:
                        event = header["event"]

                        if event == "task-started":
                            print("Task started")
                            self.task_started = True

                            # Send continue-task command. When using SSML, this command can only be sent once
                            # Special characters need to be escaped
                            self.send_continue_task("<speak rate=\"2\">I am speaking faster than usual.</speak>")

                            # Send finish-task after continue-task is sent
                            self.send_finish_task()

                        elif event == "task-finished":
                            print("Task completed")
                            self.task_finished = True
                            self.close(ws)

                        elif event == "task-failed":
                            error_msg = msg_json.get("error_message", "Unknown error")
                            print(f"Task failed: {error_msg}")
                            self.task_finished = True
                            self.close(ws)

            except json.JSONDecodeError as e:
                print(f"JSON parsing failed: {e}")
        else:
            # Process binary messages (audio data)
            print(f"Received binary message, size: {len(message)} bytes")
            with open(self.output_file, "ab") as f:
                f.write(message)
            print(f"Audio data written to local file {self.output_file}")

    def on_error(self, ws, error):
        """Callback when an error occurs"""
        print(f"WebSocket error: {error}")

    def on_close(self, ws, close_status_code, close_msg):
        """Callback when connection is closed"""
        print(f"WebSocket closed: {close_msg} ({close_status_code})")

    def send_continue_task(self, text):
        """Send continue-task command with the text content to synthesize"""
        cmd = {
            "header": {
                "action": "continue-task",
                "task_id": self.task_id,
                "streaming": "duplex"
            },
            "payload": {
                "input": {
                    "text": text
                }
            }
        }

        self.ws.send(json.dumps(cmd))
        print(f"continue-task command sent, text content: {text}")

    def send_finish_task(self):
        """Send finish-task command to end the speech synthesis task"""
        cmd = {
            "header": {
                "action": "finish-task",
                "task_id": self.task_id,
                "streaming": "duplex"
            },
            "payload": {
                "input": {}
            }
        }

        self.ws.send(json.dumps(cmd))
        print("finish-task command sent")

    def close(self, ws):
        """Actively close the connection"""
        if ws and ws.sock and ws.sock.connected:
            ws.close()
            print("Connection closed actively")

    def run(self):
        """Start the WebSocket client"""
        # Set request headers (authentication)
        header = {
            "Authorization": f"bearer {self.api_key}",
            "X-DashScope-DataInspection": "enable"
        }

        # Create WebSocketApp instance
        self.ws = websocket.WebSocketApp(
            self.uri,
            header=header,
            on_open=self.on_open,
            on_message=self.on_message,
            on_error=self.on_error,
            on_close=self.on_close
        )

        print("Listening for WebSocket messages...")
        self.ws.run_forever()  # Start persistent connection listener

# Example usage
if __name__ == "__main__":
    # The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
    # If you have not configured an environment variable, replace the following line with your Model Studio API Key: API_KEY = "sk-xxx"
    API_KEY = os.environ.get("DASHSCOPE_API_KEY")
    # Singapore region URL. Replace WorkspaceId with your actual workspace ID. The URL varies by region.
    SERVER_URI = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference/"

    client = TTSClient(API_KEY, SERVER_URI)
    client.run()

Go

// SSML feature description:
//     1. When sending the run-task command, set the enable_ssml parameter to true to enable SSML support
//     2. Send text containing SSML via the continue-task command, and only one continue-task command is allowed
// Use an SSML-compatible cloned or preset voice (such as longanyang for cosyvoice-v3-flash). See this page for supported models.

package main

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

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

const (
    // Singapore region URL. Replace WorkspaceId with your actual workspace ID. The URL varies by region.
    wsURL      = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference/"
    outputFile = "output.mp3"
)

func main() {
    // The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
    // If you have not configured an environment variable, replace the following line with your Model Studio API Key: apiKey := "sk-xxx"
    apiKey := os.Getenv("DASHSCOPE_API_KEY")

    // Clear the output file
    os.Remove(outputFile)
    os.Create(outputFile)

    // Connect to WebSocket
    header := make(http.Header)
    header.Add("X-DashScope-DataInspection", "enable")
    header.Add("Authorization", fmt.Sprintf("bearer %s", apiKey))

    conn, resp, err := websocket.DefaultDialer.Dial(wsURL, header)
    if err != nil {
        if resp != nil {
            fmt.Printf("Connection failed, HTTP status code: %d\n", resp.StatusCode)
        }
        fmt.Println("Connection failed:", err)
        return
    }
    defer conn.Close()

    // Generate task ID
    taskID := uuid.New().String()
    fmt.Printf("Generated task ID: %s\n", taskID)

    // Send run-task command
    runTaskCmd := map[string]interface{}{
        "header": map[string]interface{}{
            "action":    "run-task",
            "task_id":   taskID,
            "streaming": "duplex",
        },
        "payload": map[string]interface{}{
            "task_group": "audio",
            "task":       "tts",
            "function":   "SpeechSynthesizer",
            "model":      "cosyvoice-v3-flash",
            "parameters": map[string]interface{}{
                "text_type":   "PlainText",
                "voice":       "longanyang",
                "format":      "mp3",
                "sample_rate": 22050,
                "volume":      50,
                "rate":        1,
                "pitch":       1,
                // If enable_ssml is set to true, only one continue-task command is allowed; otherwise the error "Text request limit violated, expected 1." will be returned
                "enable_ssml": true,
            },
            "input": map[string]interface{}{},
        },
    }

    runTaskJSON, _ := json.Marshal(runTaskCmd)
    fmt.Printf("Sending run-task command: %s\n", string(runTaskJSON))

    err = conn.WriteMessage(websocket.TextMessage, runTaskJSON)
    if err != nil {
        fmt.Println("Failed to send run-task:", err)
        return
    }

    textSent := false

    // Process messages
    for {
        messageType, message, err := conn.ReadMessage()
        if err != nil {
            fmt.Println("Failed to read message:", err)
            break
        }

        // Process binary messages
        if messageType == websocket.BinaryMessage {
            fmt.Printf("Received binary message, length: %d\n", len(message))
            file, _ := os.OpenFile(outputFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
            file.Write(message)
            file.Close()
            continue
        }

        // Process text messages
        messageStr := string(message)
        fmt.Printf("Received text message: %s\n", strings.ReplaceAll(messageStr, "\n", ""))

        // Simple JSON parsing to get event type
        var msgMap map[string]interface{}
        if json.Unmarshal(message, &msgMap) == nil {
            if header, ok := msgMap["header"].(map[string]interface{}); ok {
                if event, ok := header["event"].(string); ok {
                    fmt.Printf("Event type: %s\n", event)

                    switch event {
                    case "task-started":
                        fmt.Println("=== Received task-started event ===")

                        if !textSent {
                            // Send continue-task command. When using SSML, this command can only be sent once
                            continueTaskCmd := map[string]interface{}{
                                "header": map[string]interface{}{
                                    "action":    "continue-task",
                                    "task_id":   taskID,
                                    "streaming": "duplex",
                                },
                                "payload": map[string]interface{}{
                                    "input": map[string]interface{}{
                                        // Special characters need to be escaped
                                        "text": "<speak rate=\"2\">I am speaking faster than usual.</speak>",
                                    },
                                },
                            }

                            continueTaskJSON, _ := json.Marshal(continueTaskCmd)
                            fmt.Printf("Sending continue-task command: %s\n", string(continueTaskJSON))

                            err = conn.WriteMessage(websocket.TextMessage, continueTaskJSON)
                            if err != nil {
                                fmt.Println("Failed to send continue-task:", err)
                                return
                            }

                            textSent = true

                            // Delay before sending finish-task
                            time.Sleep(500 * time.Millisecond)

                            // Send finish-task command
                            finishTaskCmd := map[string]interface{}{
                                "header": map[string]interface{}{
                                    "action":    "finish-task",
                                    "task_id":   taskID,
                                    "streaming": "duplex",
                                },
                                "payload": map[string]interface{}{
                                    "input": map[string]interface{}{},
                                },
                            }

                            finishTaskJSON, _ := json.Marshal(finishTaskCmd)
                            fmt.Printf("Sending finish-task command: %s\n", string(finishTaskJSON))

                            err = conn.WriteMessage(websocket.TextMessage, finishTaskJSON)
                            if err != nil {
                                fmt.Println("Failed to send finish-task:", err)
                                return
                            }
                        }

                    case "task-finished":
                        fmt.Println("=== Task completed ===")
                        return

                    case "task-failed":
                        fmt.Println("=== Task failed ===")
                        if header["error_message"] != nil {
                            fmt.Printf("Error message: %s\n", header["error_message"])
                        }
                        return

                    case "result-generated":
                        fmt.Println("Received result-generated event")
                    }
                }
            }
        }
    }
}

C#

using System.Net.WebSockets;
using System.Text;
using System.Text.Json;

// SSML feature description:
//     1. When sending the run-task command, set the enable_ssml parameter to true to enable SSML support
//     2. Send text containing SSML via the continue-task command, and only one continue-task command is allowed
// Use an SSML-compatible cloned or preset voice (such as longanyang for cosyvoice-v3-flash). See this page for supported models.
class Program {
    // The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
    // If you have not configured an environment variable, replace the following line with your Model Studio API Key: private static readonly string ApiKey = "sk-xxx"
    private static readonly string ApiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");

    // Singapore region URL. Replace WorkspaceId with your actual workspace ID. The URL varies by region.
    private const string WebSocketUrl = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference/";
    // Output file path
    private const string OutputFilePath = "output.mp3";

    // WebSocket client
    private static ClientWebSocket _webSocket = new ClientWebSocket();
    // Cancellation token source
    private static CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
    // Task ID
    private static string? _taskId;
    // Whether the task has started
    private static TaskCompletionSource<bool> _taskStartedTcs = new TaskCompletionSource<bool>();

    static async Task Main(string[] args) {
        try {
            // Clear the output file
            ClearOutputFile(OutputFilePath);

            // Connect to the WebSocket service
            await ConnectToWebSocketAsync(WebSocketUrl);

            // Start the message receiving task
            Task receiveTask = ReceiveMessagesAsync();

            // Send run-task command
            _taskId = GenerateTaskId();
            await SendRunTaskCommandAsync(_taskId);

            // Wait for the task-started event
            await _taskStartedTcs.Task;

            // Send continue-task command. When using SSML, this command can only be sent once
            // Special characters need to be escaped
            await SendContinueTaskCommandAsync("<speak rate=\"2\">I am speaking faster than usual.</speak>");

            // Send finish-task command
            await SendFinishTaskCommandAsync(_taskId);

            // Wait for the receiving task to complete
            await receiveTask;

            Console.WriteLine("Task completed, connection closed.");
        } catch (OperationCanceledException) {
            Console.WriteLine("Task was cancelled.");
        } catch (Exception ex) {
            Console.WriteLine($"An error occurred: {ex.Message}");
        } finally {
            _cancellationTokenSource.Cancel();
            _webSocket.Dispose();
        }
    }

    private static void ClearOutputFile(string filePath) {
        if (File.Exists(filePath)) {
            File.WriteAllText(filePath, string.Empty);
            Console.WriteLine("Output file cleared.");
        } else {
            Console.WriteLine("Output file does not exist, no need to clear.");
        }
    }

    private static async Task ConnectToWebSocketAsync(string url) {
        var uri = new Uri(url);
        if (_webSocket.State == WebSocketState.Connecting || _webSocket.State == WebSocketState.Open) {
            return;
        }

        // Set WebSocket connection headers
        _webSocket.Options.SetRequestHeader("Authorization", $"bearer {ApiKey}");
        _webSocket.Options.SetRequestHeader("X-DashScope-DataInspection", "enable");

        try {
            await _webSocket.ConnectAsync(uri, _cancellationTokenSource.Token);
            Console.WriteLine("Successfully connected to the WebSocket service.");
        } catch (OperationCanceledException) {
            Console.WriteLine("WebSocket connection was cancelled.");
        } catch (Exception ex) {
            Console.WriteLine($"WebSocket connection failed: {ex.Message}");
            throw;
        }
    }

    private static async Task SendRunTaskCommandAsync(string taskId) {
        var command = CreateCommand("run-task", taskId, "duplex", new {
            task_group = "audio",
            task = "tts",
            function = "SpeechSynthesizer",
            model = "cosyvoice-v3-flash",
            parameters = new
            {
                text_type = "PlainText",
                voice = "longanyang",
                format = "mp3",
                sample_rate = 22050,
                volume = 50,
                rate = 1,
                pitch = 1,
                // If enable_ssml is set to true, only one continue-task command is allowed; otherwise the error "Text request limit violated, expected 1." will be returned
                enable_ssml = true
            },
            input = new { }
        });

        await SendJsonMessageAsync(command);
        Console.WriteLine("run-task command sent.");
    }

    private static async Task SendContinueTaskCommandAsync(string text) {
        if (_taskId == null) {
            throw new InvalidOperationException("Task ID is not initialized.");
        }

        var command = CreateCommand("continue-task", _taskId, "duplex", new {
            input = new {
                text
            }
        });

        await SendJsonMessageAsync(command);
        Console.WriteLine("continue-task command sent.");
    }

    private static async Task SendFinishTaskCommandAsync(string taskId) {
        var command = CreateCommand("finish-task", taskId, "duplex", new {
            input = new { }
        });

        await SendJsonMessageAsync(command);
        Console.WriteLine("finish-task command sent.");
    }

    private static async Task SendJsonMessageAsync(string message) {
        var buffer = Encoding.UTF8.GetBytes(message);
        try {
            await _webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, _cancellationTokenSource.Token);
        } catch (OperationCanceledException) {
            Console.WriteLine("Message sending was cancelled.");
        }
    }

    private static async Task ReceiveMessagesAsync() {
        while (_webSocket.State == WebSocketState.Open) {
            var response = await ReceiveMessageAsync();
            if (response != null) {
                var eventStr = response.RootElement.GetProperty("header").GetProperty("event").GetString();
                switch (eventStr) {
                    case "task-started":
                        Console.WriteLine("Task started.");
                        _taskStartedTcs.TrySetResult(true);
                        break;
                    case "task-finished":
                        Console.WriteLine("Task finished.");
                        _cancellationTokenSource.Cancel();
                        break;
                    case "task-failed":
                        Console.WriteLine("Task failed: " + response.RootElement.GetProperty("header").GetProperty("error_message").GetString());
                        _cancellationTokenSource.Cancel();
                        break;
                    default:
                        // result-generated can be handled here
                        break;
                }
            }
        }
    }

    private static async Task<JsonDocument?> ReceiveMessageAsync() {
        var buffer = new byte[1024 * 4];
        var segment = new ArraySegment<byte>(buffer);

        try {
            WebSocketReceiveResult result = await _webSocket.ReceiveAsync(segment, _cancellationTokenSource.Token);

            if (result.MessageType == WebSocketMessageType.Close) {
                await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", _cancellationTokenSource.Token);
                return null;
            }

            if (result.MessageType == WebSocketMessageType.Binary) {
                // Process binary data
                Console.WriteLine("Received binary data...");

                // Save binary data to file
                using (var fileStream = new FileStream(OutputFilePath, FileMode.Append)) {
                    fileStream.Write(buffer, 0, result.Count);
                }

                return null;
            }

            string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
            return JsonDocument.Parse(message);
        } catch (OperationCanceledException) {
            Console.WriteLine("Message receiving was cancelled.");
            return null;
        }
    }

    private static string GenerateTaskId() {
        return Guid.NewGuid().ToString("N").Substring(0, 32);
    }

    private static string CreateCommand(string action, string taskId, string streaming, object payload) {
        var command = new {
            header = new {
                action,
                task_id = taskId,
                streaming
            },
            payload
        };

        return JsonSerializer.Serialize(command);
    }
}

PHP

The directory structure of the sample code is as follows:

my-php-project/

├── composer.json

├── vendor/

└── index.php

The content of composer.json is as follows. Decide the versions of the related dependencies based on your actual situation:

{
    "require": {
        "react/event-loop": "^1.3",
        "react/socket": "^1.11",
        "react/stream": "^1.2",
        "react/http": "^1.1",
        "ratchet/pawl": "^0.4"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

The content of index.php is as follows:

<!-- SSML feature description: -->
<!--     1. When sending the run-task command, set the enable_ssml parameter to true to enable SSML support -->
<!--     2. Send text containing SSML via the continue-task command, and only one continue-task command is allowed -->
<!--     3. For qwen-audio-3.0-tts-flash, qwen-audio-3.0-tts-plus, cosyvoice-v3-flash, cosyvoice-v3-plus, and cosyvoice-v2, use a cloned voice or a system voice marked as supporting SSML (for example, longanyang for cosyvoice-v3-flash). -->

<?php

require __DIR__ . '/vendor/autoload.php';

use Ratchet\Client\Connector;
use React\EventLoop\Loop;
use React\Socket\Connector as SocketConnector;

// The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
// If you have not configured an environment variable, replace the following line with your Model Studio API Key: $api_key = "sk-xxx"
$api_key = getenv("DASHSCOPE_API_KEY");
// Singapore region URL. Replace WorkspaceId with your actual workspace ID. The URL varies by region.
$websocket_url = 'wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference/'; // WebSocket server address
$output_file = 'output.mp3'; // Output file path

$loop = Loop::get();

if (file_exists($output_file)) {
    // Clear file contents
    file_put_contents($output_file, '');
}

// Create a custom connector
$socketConnector = new SocketConnector($loop, [
    'tcp' => [
        'bindto' => '0.0.0.0:0',
    ],
    'tls' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
    ],
]);

$connector = new Connector($loop, $socketConnector);

$headers = [
    'Authorization' => 'bearer ' . $api_key,
    'X-DashScope-DataInspection' => 'enable'
];

$connector($websocket_url, [], $headers)->then(function ($conn) use ($loop, $output_file) {
    echo "Connected to WebSocket server\n";

    // Generate task ID
    $taskId = generateTaskId();

    // Send run-task command
    sendRunTaskMessage($conn, $taskId);

    // Define the function to send continue-task command
    $sendContinueTask = function() use ($conn, $loop, $taskId) {
        // Send continue-task command. When using SSML, this command can only be sent once
        $continueTaskMessage = json_encode([
            "header" => [
                "action" => "continue-task",
                "task_id" => $taskId,
                "streaming" => "duplex"
            ],
            "payload" => [
                "input" => [
                    // Special characters need to be escaped
                    "text" => "<speak rate=\"2\">I am speaking faster than usual.</speak>"
                ]
            ]
        ]);
        $conn->send($continueTaskMessage);

        // Send finish-task command
        sendFinishTaskMessage($conn, $taskId);
    };

    // Flag for whether task-started event has been received
    $taskStarted = false;

    // Listen for messages
    $conn->on('message', function($msg) use ($conn, $sendContinueTask, $loop, &$taskStarted, $taskId, $output_file) {
        if ($msg->isBinary()) {
            // Write binary data to local file
            file_put_contents($output_file, $msg->getPayload(), FILE_APPEND);
        } else {
            // Process non-binary messages
            $response = json_decode($msg, true);

            if (isset($response['header']['event'])) {
                handleEvent($conn, $response, $sendContinueTask, $loop, $taskId, $taskStarted);
            } else {
                echo "Unknown message format\n";
            }
        }
    });

    // Listen for connection close
    $conn->on('close', function($code = null, $reason = null) {
        echo "Connection closed\n";
        if ($code !== null) {
            echo "Close code: " . $code . "\n";
        }
        if ($reason !== null) {
            echo "Close reason: " . $reason . "\n";
        }
    });
}, function ($e) {
    echo "Unable to connect: {$e->getMessage()}\n";
});

$loop->run();

/**
 * Generate task ID
 * @return string
 */
function generateTaskId(): string {
    return bin2hex(random_bytes(16));
}

/**
 * Send run-task command
 * @param $conn
 * @param $taskId
 */
function sendRunTaskMessage($conn, $taskId) {
    $runTaskMessage = json_encode([
        "header" => [
            "action" => "run-task",
            "task_id" => $taskId,
            "streaming" => "duplex"
        ],
        "payload" => [
            "task_group" => "audio",
            "task" => "tts",
            "function" => "SpeechSynthesizer",
            "model" => "cosyvoice-v3-flash",
            "parameters" => [
                "text_type" => "PlainText",
                "voice" => "longanyang",
                "format" => "mp3",
                "sample_rate" => 22050,
                "volume" => 50,
                "rate" => 1,
                "pitch" => 1,
                // If enable_ssml is set to true, only one continue-task command is allowed; otherwise the error "Text request limit violated, expected 1." will be returned
                "enable_ssml" => true
            ],
            "input" => (object) []
        ]
    ]);
    echo "Preparing to send run-task command: " . $runTaskMessage . "\n";
    $conn->send($runTaskMessage);
    echo "run-task command sent\n";
}

/**
 * Read audio file
 * @param string $filePath
 * @return bool|string
 */
function readAudioFile(string $filePath) {
    $voiceData = file_get_contents($filePath);
    if ($voiceData === false) {
        echo "Unable to read audio file\n";
    }
    return $voiceData;
}

/**
 * Split audio data
 * @param string $data
 * @param int $chunkSize
 * @return array
 */
function splitAudioData(string $data, int $chunkSize): array {
    return str_split($data, $chunkSize);
}

/**
 * Send finish-task command
 * @param $conn
 * @param $taskId
 */
function sendFinishTaskMessage($conn, $taskId) {
    $finishTaskMessage = json_encode([
        "header" => [
            "action" => "finish-task",
            "task_id" => $taskId,
            "streaming" => "duplex"
        ],
        "payload" => [
            "input" => (object) []
        ]
    ]);
    echo "Preparing to send finish-task command: " . $finishTaskMessage . "\n";
    $conn->send($finishTaskMessage);
    echo "finish-task command sent\n";
}

/**
 * Handle events
 * @param $conn
 * @param $response
 * @param $sendContinueTask
 * @param $loop
 * @param $taskId
 * @param $taskStarted
 */
function handleEvent($conn, $response, $sendContinueTask, $loop, $taskId, &$taskStarted) {
    switch ($response['header']['event']) {
        case 'task-started':
            echo "Task started, sending continue-task command...\n";
            $taskStarted = true;
            // Send continue-task command
            $sendContinueTask();
            break;
        case 'result-generated':
            // Ignore result-generated events
            break;
        case 'task-finished':
            echo "Task completed\n";
            $conn->close();
            break;
        case 'task-failed':
            echo "Task failed\n";
            echo "Error code: " . $response['header']['error_code'] . "\n";
            echo "Error message: " . $response['header']['error_message'] . "\n";
            $conn->close();
            break;
        case 'error':
            echo "Error: " . $response['payload']['message'] . "\n";
            break;
        default:
            echo "Unknown event: " . $response['header']['event'] . "\n";
            break;
    }

    // If the task is completed, close the connection
    if ($response['header']['event'] == 'task-finished') {
        // Wait 1 second to ensure all data has been transmitted
        $loop->addTimer(1, function() use ($conn) {
            $conn->close();
            echo "Client closed connection\n";
        });
    }

    // If task-started event has not been received, close the connection
    if (!$taskStarted && in_array($response['header']['event'], ['task-failed', 'error'])) {
        $conn->close();
    }
}

Node.js

Install the related dependencies:

npm install ws
npm install uuid

The sample code is as follows:

// SSML feature description:
//     1. When sending the run-task command, set the enable_ssml parameter to true to enable SSML support
//     2. Send text containing SSML via the continue-task command, and only one continue-task command is allowed
// Use an SSML-compatible cloned or preset voice (such as longanyang for cosyvoice-v3-flash). See this page for supported models.

import fs from 'fs';
import WebSocket from 'ws';
import { v4 as uuid } from 'uuid'; // For generating UUIDs

// The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
// If you have not configured an environment variable, replace the following line with your Model Studio API Key: const apiKey = "sk-xxx"
const apiKey = process.env.DASHSCOPE_API_KEY;
// Singapore region URL. Replace WorkspaceId with your actual workspace ID. The URL varies by region.
const url = 'wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference/';
// Output file path
const outputFilePath = 'output.mp3';

// Clear the output file
fs.writeFileSync(outputFilePath, '');

// Create WebSocket client
const ws = new WebSocket(url, {
  headers: {
    Authorization: `bearer ${apiKey}`,
    'X-DashScope-DataInspection': 'enable'
  }
});

let taskStarted = false;
let taskId = uuid();

ws.on('open', () => {
  console.log('Connected to WebSocket server');

  // Send run-task command
  const runTaskMessage = JSON.stringify({
    header: {
      action: 'run-task',
      task_id: taskId,
      streaming: 'duplex'
    },
    payload: {
      task_group: 'audio',
      task: 'tts',
      function: 'SpeechSynthesizer',
      model: 'cosyvoice-v3-flash',
      parameters: {
        text_type: 'PlainText',
        voice: 'longanyang', // Voice
        format: 'mp3', // Audio format
        sample_rate: 22050, // Sample rate
        volume: 50, // Volume
        rate: 1, // Speech rate
        pitch: 1, // Pitch
        enable_ssml: true // Whether to enable SSML. If enable_ssml is set to true, only one continue-task command is allowed; otherwise the error "Text request limit violated, expected 1." will be returned
      },
      input: {}
    }
  });
  ws.send(runTaskMessage);
  console.log('run-task message sent');
});

const fileStream = fs.createWriteStream(outputFilePath, { flags: 'a' });
ws.on('message', (data, isBinary) => {
  if (isBinary) {
    // Write binary data to file
    fileStream.write(data);
  } else {
    const message = JSON.parse(data);

    switch (message.header.event) {
      case 'task-started':
        taskStarted = true;
        console.log('Task started');
        // Send continue-task command
        sendContinueTasks(ws);
        break;
      case 'task-finished':
        console.log('Task completed');
        ws.close();
        fileStream.end(() => {
          console.log('File stream closed');
        });
        break;
      case 'task-failed':
        console.error('Task failed:', message.header.error_message);
        ws.close();
        fileStream.end(() => {
          console.log('File stream closed');
        });
        break;
      default:
        // result-generated can be handled here
        break;
    }
  }
});

function sendContinueTasks(ws) {

  if (taskStarted) {
    // Send continue-task command. When using SSML, this command can only be sent once
    const continueTaskMessage = JSON.stringify({
      header: {
        action: 'continue-task',
        task_id: taskId,
        streaming: 'duplex'
      },
      payload: {
        input: {
          // Special characters need to be escaped
          text: '<speak rate="2">I am speaking faster than usual.</speak>'
        }
      }
    });
    ws.send(continueTaskMessage);

    // Send finish-task command
    const finishTaskMessage = JSON.stringify({
      header: {
        action: 'finish-task',
        task_id: taskId,
        streaming: 'duplex'
      },
      payload: {
        input: {}
      }
    });
    ws.send(finishTaskMessage);
  }
}

ws.on('close', () => {
  console.log('Disconnected from WebSocket server');
});

LaTeX

Usage

Wrap the mathematical formula with separators, then call the speech synthesis API.

Supported separators (choose either one; the effect is the same):

  • $...$
  • $$...$$
  • \(...\)
  • \[...\]

Example input:

这是一道分数:$\frac{1}{2}$。

The fraction is read in Chinese as “二分之一” (one half).

Formulas that contain multiple operators also use the same separators, for example:

这是一道一元二次方程的求根公式:$x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}$,请仔细计算。

In plain strings in JSON and languages such as Python, Java, and JavaScript, the backslash \ must be written as \\. For example, \frac in a formula must be written as \\frac in a plain string.

QuickStart

The following Python example synthesizes Chinese text that contains fractions and saves the result as output.mp3. For how to prepare the API Key and SDK, see the SSML QuickStart.

# coding=utf-8

import os

import dashscope

# If you have not configured an environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
# The following is the configuration for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
client = dashscope.Client(
    api_key=os.environ.get('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

model = "cosyvoice-v3-flash"
voice = "longanyang"

# Escape each backslash as \\ in a regular string.
audio = client.audio.tts.synthesize("这是一道分数:$\\frac{1}{2}$。", model=model, voice=voice)

with open('output.mp3', 'wb') as f:
    f.write(audio)

SSML tags

NoteThe implementation references the W3C SSML 1.0 specification. The supported tags are subject to the descriptions below; not all standard tags are supported.

<speak>: root node

<speak> is the root node of all SSML tags. When you use SSML features, the text content must be enclosed in <speak></speak> tags.

<speak>Text that requires SSML processing</speak>

Attributes

Attribute name

Attribute type

Required

Description

voice

String

No

Specifies the speaker (voice).

This attribute takes precedence over the speaker specified by the voice API request parameter.

rate

String

No

Specifies the speech rate. This attribute takes precedence over the speech rate specified by the API request parameter rate.

  • Value range: a decimal between [0.5,2]

  • Default value: 1

    • Greater than 1 indicates a faster speech rate
    • Less than 1 indicates a slower speech rate

pitch

String

No

Specifies the pitch. This attribute takes precedence over the pitch specified by the API request parameter pitch.

  • Value range: a decimal between [0.5,2]

  • Default value: 1

    • Greater than 1 indicates a higher pitch
    • Less than 1 indicates a lower pitch

volume

String

No

Specifies the volume. This attribute takes precedence over the volume specified by the API request parameter volume.

  • Value range: an integer between [0,100]

  • Default value: 50

    • Greater than 50 indicates a louder volume
    • Less than 50 indicates a softer volume

effect

String

No

Specifies the sound effect.

  • Value range:

    • robot: robot voice effect
    • lolita: lolita voice effect
    • lowpass: low-pass effect
    • echo: echo effect
    • eq: equalizer (advanced)
    • lpfilter: low-pass filter (advanced)
    • hpfilter: high-pass filter (advanced)

    Note

    • eq, lpfilter, and hpfilter are advanced sound effect types, and their specific effects can be customized via the effectValue parameter.
    • Each SSML tag supports only one sound effect; setting multiple effect attributes at the same time is not allowed.
    • Enabling the sound effect feature increases the synthesis latency.

effectValue

String

No

Used to further configure the specific effects of the sound effect (the effect parameter), applicable to the three advanced sound effect types: eq, lpfilter, and hpfilter.

  • Value range:

    • eq (equalizer): The system supports 8 frequency levels by default, with the corresponding frequencies as follows:

      [“40 Hz”,“100 Hz”, “200 Hz”, “400 Hz”, “800 Hz”, “1600 Hz”, “4000 Hz”, “12000 Hz”]。

      The bandwidth of each frequency band is 1.0q.

      Specify the gain value of each frequency band via the effectValue parameter: this parameter is a string consisting of 8 integers, with values in the range [-20, 20], separated by spaces. A value of 0 means no adjustment to the gain of the corresponding frequency.

      For example: effectValue="1 1 1 1 1 1 1 1"

    • lpfilter (low-pass filter): specifies the cutoff frequency of the low-pass filter, an integer in the range (0, target sample rate/2]. For example, effectValue="800".

    • hpfilter (high-pass filter): specifies the cutoff frequency of the high-pass filter, an integer in the range (0, target sample rate/2]. For example, effectValue="1200".

bgm

String

No

Adds background music to the synthesized speech.

The audio file must be stored on Alibaba Cloud OSS and be accessible via a public network URL. For how to upload files, see Upload files. For private files, use a valid signed URL. XML special characters in the URL must be escaped; for example, write & as &amp;.

  • Audio requirements:

    There is no upper limit on the background audio file size, but larger files take longer to download. If the duration of the synthesized speech exceeds that of the background audio, the background audio will automatically loop.

    • Sampling rate: 16kHz

    • Channels: mono

    • File format: WAV

      If the original audio is not in WAV format, you can use the ffmpeg tool to convert it:

      ffmpeg -i input_audio -acodec pcm_s16le -ac 1 -ar 16000 output.wav
      
    • Bit depth: 16 bits

ImportantThe uploader shall bear the corresponding legal responsibility for the copyright of the uploaded audio.

backgroundMusicVolume

String

No

Specifies the volume of the background music. Must be used together with the bgm attribute.

Examples

Empty attributes

<speak>
  Text that requires SSML tags
</speak>

Attribute combinations (separated by spaces)

<speak rate="1.5" pitch="0.8" volume="80">
  So when put together, my voice sounds like this.
</speak>

voice

<speak voice="longcheng_v2">
  I am a male voice.
</speak>

rate

<speak rate="2">
  My speech rate is faster than normal.
</speak>

pitch

<speak pitch="0.5">
  However, my pitch is lower than others.
</speak>

volume

<speak volume="80">
  My volume is also very high.
</speak>

effect

<speak effect="robot">
  Do you like the robot WALL-E?
</speak>

effectValue

<speak effect="eq" effectValue="1 -20 1 1 1 1 20 1">
  Do you like the robot WALL-E?
</speak>

<speak effect="lpfilter" effectValue="1200">
  Do you like the robot WALL-E?
</speak>

<speak effect="hpfilter" effectValue="1200">
  Do you like the robot WALL-E?
</speak>

bgm

<speak bgm="https://nls.alicdn.com/bgm/2.wav" backgroundMusicVolume="30" rate="0.8" volume="40">
  <break time="2s"/>
  The old trees on the shady cliff are shrouded in mist
  <break time="700ms"/>
  The sound of rain is still in the bamboo forest
  <break time="700ms"/>
  I know that cotton contributes to the country's plan
  <break time="700ms"/>
  The scenery of Mianzhou is always pitiable
  <break time="2s"/>
</speak>

Tag relationships

The <speak> tag can contain text and the following child tags:

  • <break>: controls the pause duration
  • <sub>: substitute text
  • <phoneme>: specifies the pronunciation (pinyin/phonetic symbols)
  • <soundEvent>: inserts an external sound (ringtone, cat meow, etc.)
  • <say-as>: sets how text is read aloud (numbers, dates, phone numbers, etc.)

<break>: controls the pause

Inserts a silent pause during speech synthesis to simulate a natural pause in speaking. Supports two units: seconds (s) and milliseconds (ms).

<!-- No attributes -->
<break/>
<!-- With time attribute -->
<break time="string"/>

Attributes

Attribute name

Attribute type

Required

Description

time

String

No

Sets the pause duration, supporting both seconds and milliseconds (for example, "2s" or "50ms").

  • Value range:

    • In seconds (s), the value is an integer in the range [1, 10]
    • In milliseconds (ms), the value is an integer in the range [50, 10000]

When multiple <break> tags are used consecutively, the total pause duration is the sum of the durations of each tag. If the total exceeds 10 seconds, only the first 10 seconds are retained.

An <break> tag without attributes pauses for 1 second by default.

Examples

time

<speak>
  Please close your eyes and take a rest.<break time="500ms"/>Okay, please open your eyes.
</speak>

When the following three <break> tags are used consecutively, the total configured pause duration is 15 seconds, but only 10 seconds are actually retained.

<speak>
  Please close your eyes and take a rest.<break time="5s"/><break time="5s"/><break time="5s"/>Okay, please open your eyes.
</speak>

Tag relationships

<break> is a self-closing tag and cannot contain any child tags.

<sub>: substitute text

Replaces the specified text with content more suitable for reading aloud. For example, read "W3C" as "network protocol standards".

<sub alias="string"></sub>

Attributes

Attribute nameAttribute typeRequiredDescription
aliasStringYesSpecifies the spoken content that replaces the original text.

Examples

alias

<speak>
  <sub alias="World Wide Web Consortium">W3C</sub>
</speak>

Tag relationships

<sub> tags can only contain plain text.

<phoneme>: specify pronunciation

Precisely controls how text is pronounced. For Chinese, pronunciation can be specified with pinyin; for English, CMU phonetic symbols can be used. It applies to scenarios such as disambiguating polyphonic characters and pronouncing foreign words.

<phoneme alphabet="string" ph="string">Text</phoneme>

Attributes

Attribute name

Attribute type

Required

Description

alphabet

String

Yes

Specifies the pronunciation type: pinyin (for Chinese) or phonetic symbols (for English).

Value range:

ph

String

Yes

Specifies the specific pinyin or phonetic symbols. Usage rules:

  • Separate the pinyin of multiple Chinese characters with spaces, and the number of pinyin syllables must match the number of characters.
  • Each pinyin syllable consists of the pronunciation and the tone, where the tone is an integer from 1 to 5, and 5 indicates the neutral tone.

Examples

ph

<speak>
  去<phoneme alphabet="py" ph="dian3 dang4 hang2">典当行</phoneme>把这个玩意<phoneme alphabet="py" ph="dang4 diao4">当掉</phoneme>
</speak>

<speak>
  How to spell <phoneme alphabet="cmu" ph="S AY N">sin</phoneme>?
</speak>

Tag relationships

<phoneme> tags can only contain plain text.

<soundEvent>: Insert a sound effect

Inserts a sound effect file (such as a prompt tone or ambient sound) at a specified position in the speech to enrich the expressiveness of the voice.

<soundEvent src="URL"/>

Attributes

Attribute name

Attribute type

Required

Description

src

String

Yes

Specifies the URL of an external audio file.

The audio file must be stored on Alibaba Cloud OSS and be accessible via a public network URL. For how to upload files, see Upload files. For private files, use a valid signed URL. XML special characters in the URL must be escaped; for example, write & as &amp;.

  • Audio requirements:

    • Sampling rate: 16kHz

    • Channels: mono

    • File format: WAV

      If the original audio is not in WAV format, you can use the ffmpeg tool to convert it:

      ffmpeg -i input_audio -acodec pcm_s16le -ac 1 -ar 16000 output.wav
      
    • File size: no more than 2 MB

    • Bit depth: 16 bits

ImportantThe uploader shall bear the corresponding legal responsibility for the copyright of the uploaded audio.

Examples

src

<speak>
  A horse was frightened<soundEvent src="https://nls.alicdn.com/sound-event/horse-neigh.wav"/>and people scattered to avoid it.
</speak>

Tag relationships

<soundEvent> is a self-closing tag and cannot contain any child tags.

<say-as>: Set reading rules

Specifies the content type of the text (such as numbers, dates, or phone numbers), and the system reads it aloud according to the standard reading rules for the corresponding type.

<say-as interpret-as="string">Text</say-as>

Attributes

Attribute name

Attribute type

Required

Description

interpret-as

String

Yes

Specifies the content type of the text within the tag.

Value range:

  • cardinal: reads the text as a standard integer or decimal
  • digits: reads each digit one by one (e.g., 123 → one two three)
  • telephone: reads digit by digit in the standard way for phone numbers
  • name: reads according to the standard reading rules for personal names
  • address: reads according to the standard reading rules for addresses
  • id: reads according to the standard reading rules for identifiers (such as account names or nicknames)
  • characters: reads the text within the tag character by character
  • punctuation: reads out the names of punctuation marks within the tag
  • date: reads according to the standard reading rules for date formats
  • time: reads according to the standard reading rules for time formats
  • currency: reads according to the standard reading rules for monetary amounts
  • measure: reads according to the standard reading rules for units of measurement

Click to view the supported scope of say-as

cardinal

Chinese

Format

Examples

Chinese output

Description

Digit string

145

One hundred and forty-five

Integer input range: positive and negative integers within 20 digits, [-99999999999999999999,99999999999999999999]. Decimal input range: there is no special limit on the number of digits after the decimal point, but no more than 10 digits are recommended.

Minus sign + digit string

-145

Minus one hundred and forty-five

Digit string separated by commas every 3 digits

10,000

Ten thousand

Minus sign + digit string separated by commas every 3 digits

-10,124

Minus ten thousand one hundred and twenty-four

Digit string + decimal point + 2 zeros

10.00

Ten

Minus sign + digit string + decimal point + 2 zeros

-110.00

Minus one hundred and ten

Digit string + decimal point + digit string

79.090

Seventy-nine point zero nine zero

Minus sign + digit string + decimal point + digit string

-79.001

minus seventy-nine point zero zero one

English

Format

Examples

English output

Description

Digit string

145

one hundred forty five

Integer input range: positive and negative integers within 13 digits, [-999999999999,999999999999].

Decimal input range: there is no special limit on the number of digits after the decimal point; no more than 10 digits are recommended.

Digit string starting with zero

0145

one hundred forty five

Minus sign + digit string

-145

minus hundred forty five

Digit string with three-digit groups separated by commas

60,000

sixty thousand

Minus sign + digit string with comma-separated three-digit groups

-208,000

minus two hundred eight thousand

Digit string + decimal point + zero

12.00

twelve

Digit string + decimal point + digit string

12.34

twelve point three four

Comma-separated three-digit digit string + decimal point + digit string

1,000.1

one thousand point one

Minus sign + digit string + decimal point + digit string

-12.34

minus twelve point three four

Minus sign + comma-separated three-digit digit string + decimal point + digit string

-1,000.1

minus one thousand point one

(Comma-separated three-digit) digit string + hyphen + (comma-separated three-digit) digits

1-1,000

one to one thousand

Other default readings

012.34

twelve point three four

None

1/2

one half

-3/4

minus three quarters

5.1/6

five point one over six

-3 1/2

minus three and a half

1,000.3^3

one thousand point three to the power of three

3e9.1

three times ten to the power of nine point one

23.10%

twenty three point one percent

digits

Chinese

FormatExamplesChinese outputDescription
Digit string129090909one two nine zero nine zero nine zero nineThere is no special limit on the length of the digit string; no more than 20 digits are recommended. When the digit string exceeds 10 digits, a pause is inserted after each digit.

English

Format

Examples

English output

Description

Digit string

12034

one two zero three four

There is no special limit on the length of the digit string; no more than 20 digits are recommended.

When the digit string is grouped by spaces or hyphens, a comma is inserted between groups to produce an appropriate pause; up to 5 groups are supported.

Digit string + space or hyphen + digit string + space or hyphen + digit string + space or hyphen + digit string

1-23-456 7890

one, two three, four five six, seven eight nine zero

telephone

Chinese

Format

Examples

Chinese output

Description

Landline number

4930286

four nine three zero two eight six

Supports 7~8-digit landline numbers, with spaces and "-" supported as separators. Specifically, 7-digit landline numbers support the "3-4" digit grouping format; 8-digit landline numbers support the "4-4" digit grouping format.

493 0286

four nine three zero two eight six

493-0286

four nine three zero two eight six

62552560

six two five five two five six zero

6255 2560

six two five five two five six zero

6255-2560

six two five five two five six zero

Landline number + extension number

4930286-109

four nine three zero two eight six transfer one zero nine

Supports 1~4-digit extension numbers.

4930286 transfer 109

four nine three zero two eight six transfer one zero nine

4930286 extension 109

four nine three zero two eight six extension one zero nine

4930286 extension 109

four nine three zero two eight six extension one zero nine

Area code + landline number

01062552560

zero one zero six two five five two five six zero

Supported area codes: 010, 02x, 03xx, 04xx, 05xx, 07xx, 08xx, 09xx.

010 62552560

zero one zero six two five five two five six zero

010 6255 2560

zero one zero six two five five two five six zero

010 6255-2560

zero one zero six two five five two five six zero

010-62552560

zero one zero six two five five two five six zero

010-6255-2560

zero one zero six two five five two five six zero

(010)62552560

zero one zero six two five five two five six zero

03198907098

zero three one nine eight nine zero seven zero nine eight

0319-8907098

three one nine eight nine zero seven zero nine eight

Area code + landline number + extension number

010 62552560-109

zero one zero six two five five two five six zero ext. one zero nine

None

010-62552560-109

zero one zero six two five five two five six zero ext. one zero nine

(010)62552560-109

zero one zero six two five five two five six zero ext. one zero nine

(010)62552560 ext. 109

zero one zero six two five five two five six zero ext. one zero nine

(010)62552560 ext. 109

zero one zero six two five five two five six zero ext. one zero nine

(010)62552560 extension 109

zero one zero six two five five two five six zero extension one zero nine

Country code + area code + landline number

86-010-62791627

eight six zero one zero six two seven nine one six two seven

Supported country codes: 86, (86), +86, (+86), 0086. All are uniformly read as "eight six".

(86)10-62791627

eight six one zero six two seven nine one six two seven

+86-010-62791627

eight six zero one zero six two seven nine one six two seven

0086-10-62791627

eight six one zero six two seven nine one six two seven

(+86)-10-6279 1627

eight six one zero six two seven nine one six two seven

Country code + area code + landline number + extension number

(86)21-58118818-207

eight six two one five eight one one eight eight one eight ext. two zero seven

None

(86)021-5811-8818-207

eight six zero two one five eight one one eight eight one eight ext. two zero seven

(86)021-58118818 ext. 207

eight six zero two one five eight one one eight eight one eight ext. two zero seven

(86)21-5811-8818 ext. 207

eight six two one five eight one one eight eight one eight extension two zero seven

+86-021-58118818 extension 207

eight six zero two one five eight one one eight eight one eight extension number two zero seven

Mobile number

139 0000 5678

one three nine zero zero zero zero five six seven eight

Supports 11-digit mobile numbers, with two digit grouping formats: 3-3-5 and 3-4-4

139-000-05678

one three nine zero zero zero zero five six seven eight

139 000 05678

one three nine zero zero zero zero five six seven eight

Country code + mobile phone number

+86-13900005678

86 139 0000 5678

None

(+86)-139-0000-5678

86 139 0000 5678

+8613900005678

86 139 0000 5678

0086-139 000 05678

86 139 000 05678

Service number

123

123

Common service numbers are supported. 10-digit service numbers starting with 400/800 are supported, with digits grouped in the "3-3-4" format. 16-digit numbers starting with 12530/17951/12593 are supported.

95678

95678

4008110510

400 811 0510

800-810-8888

800 810 8888

1253013520638377

12530 135 2063 8377

Others

(86)(21)9899-80800-0909

86 21 9899 80800 0909

The "digit string + separator (left and right parentheses, -)" format is supported.

English

Format

Examples

English output

Description

Digit string

12034

one two oh three four

There is no special restriction on the length of digit strings; no more than 20 digits is recommended. When a digit string is grouped by spaces or hyphens, a comma is inserted between groups to create an appropriate pause, and up to 5 groups are supported.

Digit string + space or hyphen + digit string + space or hyphen + digit string

1-23-456 7890

one, two three, four five six, seven eight nine oh

Plus sign + digit string + space or hyphen + digit string

+43-211-0567

plus four three, two one one, oh five six seven

Left parenthesis + digit string + right parenthesis + space + digit string + space or hyphen + digit string

(21) 654-3210

(two one) six five four, three two one oh

address

Chinese

Format

Examples

Chinese output

Description

Common address formats

Jiayuan 30-9, Yuanhe Town

Jiayuan 30-9, Yuanhe Town

Common address formats are supported. Here, an address refers to a standard mailing address.

No. 1107-1108, Lane 388, Shitai Road

No. 1107-1108, Lane 388, Shitai Road

3-1-3205, Jinyun Mansion, Phase 6, Huarun 24 City

3-1-3205, Jinyun Mansion, Phase 6, Huarun 24 City

Room 2006, Block 2, Shenghua Mingdu Tower

Room 2006, Block 2, Shenghua Mingdu Tower

Room 201, Unit 4, Building 5, Tingyuan, Wuchang Subdistrict

Room 201, Unit 4, Building 5, Tingyuan, Wuchang Subdistrict

No. 19, Lane 150, Furongjiang Road

No. nineteen, Lane one five zero, Furongjiang Road

English

This type is not supported for English text.

id

Chinese

Format

Examples

Chinese output

Description

string

dell0101

D E L L zero one zero one

Uppercase and lowercase English letters, Arabic numerals 0~9, and underscores. The spaces in the output indicate a pause inserted between each character, that is, the characters are read one by one.

myid_1998

M Y I D underscore one nine nine eight

AiTest

A I T E S T

English

For English text, this type works the same as characters.

characters

Chinese

Format

Examples

Chinese output

Description

string

ISBN 1-001-099098-1

I S B N one dash zero zero one dash zero nine nine zero nine eight dash one

Supports Chinese characters, uppercase and lowercase English letters, Arabic numerals 0~9, and some full-width and half-width characters. The spaces in the output indicate a pause inserted between each character, that is, the characters are read one by one. If the text within the tag contains special XML characters, they must be escaped.

x10b2345_u

x one zero b two three four five underscore u

v1.0.1

v one point zero point one

Version number 2.0

Version number two point zero

Su M MA000

Su M M A zero zero zero

Airbus A330

Airbus A three three zero

Model s01 s02 and s03

Model s zero one s zero two and s zero three

Airbus A330

Airbus A three three zero

αβγ

alpha beta gamma

English

Format

Examples

English output

Description

string

*b+3$.c-0'=α

asterisk B plus three dollar dot C dash zero apostrophe equals alpha

Supports Chinese characters, uppercase and lowercase English letters, Arabic numerals 0~9, and some full-width and half-width characters.

The spaces in the output indicate a pause inserted between each character, that is, the characters are read one by one.

If the text within the tag contains special XML characters, they must be escaped.

punctuation

Chinese

Format

Examples

Chinese output

Description

Punctuation

…

ellipsis

Supports common Chinese and English punctuation. The spaces in the output indicate a pause inserted between each character, that is, the characters are read one by one. If the text within the tag contains special XML characters, they must be escaped.

……

ellipsis

!"#$%&

exclamation mark double quote hash dollar percent and

‘()*+

single quote left parenthesis right parenthesis asterisk plus

,-./:;

comma dash dot slash colon semicolon

<=>?@

less than equal sign greater than question mark at

[\]^_

Left bracket backslash right bracket caret underscore

English

For English text, this type works the same as characters.

date

Chinese

Format

Examples

Chinese output

Description

year xx

year 71

year 71 (in Chinese numerals)

2-digit and 4-digit years are supported. Among them: 2-digit years support 60~99, 00~09, and 10~19. 4-digit years support 1000~1999 and 2000~2099.

year 04

year 04 (in Chinese numerals)

year 19

year 19 (in Chinese numerals)

year 1011

year 1011 (in Chinese numerals)

year 1998

year 1998 (in Chinese numerals)

year 2008

year 2008 (in Chinese numerals)

year xx, month xx

year 98, month 4

year 98, month 4 (in Chinese numerals)

When the month is 1 to 9, both notations with and without a leading "0" are supported. For example, "year 1908, month 4" and "year 1908, month 04".

year 1998, month 04

year 1998, month 4 (in Chinese numerals)

year 08, month 8

year 08, month 8 (in Chinese numerals)

year 2008, month 8

year 2008, month 8 (in Chinese numerals)

year xx, month xx, day xx; year xx, month xx, day xx (alternative day notation)

year 98, month 4, day 23

year 98, month 4, day 23 (in Chinese numerals)

When the day is 1 to 9, both notations with and without a leading "0" are supported. For example, "year 1908, month 4, day 8" and "year 1908, month 04, day 08".

year 1998, month 04, day 23

April 23, 1998

August 8, '08

August 8, '08

August 8, 2008

August 8, 2008

year xx, month xx, day xx; year xx, month xx, day xx (alternative day notation)

year 98, month 4, day 23

year 98, month 4, day 23 (in Chinese numerals)

When the date is between the 1st and the 9th of the month, both spellings with and without a leading "0" are supported, for example "April 8, 1908" and "April 08, 1908".

year 1998, month 04, day 23

April 23, 1998

August 8, '08

August 8, '08

August 8, 2008

August 8, 2008

MM/DD

March 20

March 20

None

August 7

August 7

Year and month abbreviation

2018/08

August 2018

"/", "-", and "." are supported as separators for abbreviations.

2018-08

August 2018

2018.08

August 2018

Year, month, and day abbreviation

2018/08/08

August 8, 2018

2018-8-8

August 8, 2018

2018.08.08

August 8, 2018

MM/DD/YYYY~MM/DD/YYYY MM/DD/YYYY~MM/DD/YYYY

September 1~30, '04

September 1 to 30, '04

"~" and "-" are supported as abbreviation markers for "to".

September 1, 2004 - June 8, 2008

September 1, 2004 to June 8, 2008

MM/DD/YYYY~DD MM/DD/YYYY~DD

September 1~30, '04

September 1 to 30, '04

September 1, 2004 - June 8, 2008

September 1, 2004 to June 8, 2008

MM/YYYY~MM/YYYY

April '01~April '10

April '01 to April '10

April 2001~April 2010

April 2001 to April 2010

MM/DD~MM/DD MM/DD~MM/DD

October 1~October 7

October 1 to October 7

October 01~October 07

October 1~October 7

xx month xx day~xx day; xx month xx day~xx day

October 1~7

October 1 to 7

October 01~07

October 1st to 7th

Year-month-day abbreviation~year-month-day abbreviation

2018/03/03~2019/01/01

March 3, 2018 to January 1, 2019

Supports "/" and "." as separators for abbreviations, and supports "~" and "-" as abbreviated markers for "to".

1997.9.9~1998.9.9

September 9, 1997 to September 9, 1998

Month-day abbreviation~month-day abbreviation

10/20~10/31

October 20 to October 31

xx~xx month; xx month~xx month

1~10 month

January to October

January~October

January to October

Month-day-year abbreviation

10/20/2018

October 20, 2018

Only 4-digit years are supported, only "/" is supported as the date separator, and only the month/day/year writing format is supported.

English

Format

Examples

English output

Description

Four digits/two digits, or four digits-two digits

2000/01

two thousand, oh one

Crosses year boundaries.

1900-01

nineteen hundred, oh one

2001-02

twenty oh one, oh two

2019-20

twenty nineteen, twenty

1998-99

nineteen ninety eight, ninety nine

1999-00

nineteen ninety nine, oh oh

A four-digit number starting with 1 or 2

2000

two thousand

A four-digit year.

1900

nineteen hundred

1905

nineteen oh five

2021

twenty twenty one

Day of week-day of week

Or

Day of week~day of week

Or

Day of week&day of week

mon-wed

monday to wednesday

If the text within the day-of-week range label contains special XML characters, they must be escaped.

tue~fri

tuesday to friday

sat&sun

saturday and sunday

DD-DD MMM, YYYY

Or

DD~DD MMM, YYYY

Or

DD&DD MMM, YYYY

19-20 Jan, 2000

the nineteen to the twentieth of january two thousand

DD indicates a two-digit date, MMM indicates a three-letter abbreviation or full word for the month, and YYYY indicates a four-digit year starting with 1 or 2.

01 ~ 10 Jul, 2020

the first to the tenth of july twenty twenty

05&06 Apr, 2009

the fifth and the sixth of april two thousand nine

MMM DD-DD

Or

MMM DD~DD

Or

MMM DD&DD

Feb 01 - 03

feburary the first to the third

MMM indicates a three-letter abbreviation or full word for the month, and DD indicates a two-digit date.

Aug 10~20

august the tenth to the twentieth

Dec 11&12

december the eleventh and the twelfth

MMM-MMM

Or

MMM~MMM

Or

MMM&MMM

Jan-Jun

january to june

MMM indicates a three-letter abbreviation or full word for the month.

jul ~ dec

july to december

sep&oct

september and october

YYYY-YYYY

Or

YYYY~YYYY

1990 - 2000

nineteen ninety to two thousand

YYYY indicates a four-digit year starting with 1 or 2.

2001~2021

two thousand one to twenty twenty one

WWW DD MMM YYYY

Sun 20 Nov 2011

sunday the twentieth of november twenty eleven

WWW indicates a three-letter abbreviation or full word for the day of the week, DD indicates a two-digit date, MMM indicates a three-letter abbreviation or full word for the month, MM indicates a two-digit month (or a three-letter abbreviation or full word), and YYYY indicates a four-digit year starting with 1 or 2.

WWW DD MMM

Sun 20 Nov

sunday the twentieth of november

WWW MMM DD YYYY

Sun Nov 20 2011

sunday november the twentieth twenty eleven

WWW MMM DD

Sun Nov 20

sunday november the twentieth

WWW YYYY-MM-DD

Sat 2010-10-01

aturday october the first twenty ten

WWW YYYY/MM/DD

Sat 2010/10/01

saturday october the first twenty ten

WWW MM/DD/YYYY

Sun 11/20/2011

sunday november the twentieth twenty eleven

MM/DD/YYYY

11/20/2011

november the twentieth twenty eleven

YYYY

1998

nineteen ninety eight

Other default readings

10 Mar, 2001

the tenth of march two thousand one

None

10 Mar

the tenth of march

Mar 2001

march two thousand one

Fri. 10/Mar/2001

friday the tenth of march two thousand one

Mar 10th, 2001

march the tenth two thousand one

Mar 10

march the tenth

2001/03/10

march the tenth two thousand one

2001-03-10

march the tenth two thousand one

2000s

two thousands

2010's

twenty tens

1900's

nineteen hundreds

1990s

nineteen nineties

time

Chinese

Format

Examples

Chinese output

Description

Time of day

12:00

Twelve o'clock

Supports common time and time range formats.

12:00:00 o'clock

Twelve o'clock

10:20

Ten twenty

10:20:30

Ten twenty and thirty seconds

09:18:14

Nine eighteen and fourteen seconds

Time of day~Time of day

11:00~12:00

Eleven o'clock to twelve o'clock

09:00-14:00

Nine o'clock to fourteen o'clock

11:00~11:30

Eleven o'clock to eleven thirty

11:00-12:18

Eleven o'clock to twelve eighteen

10:30~11:00

Ten thirty to eleven o'clock

09:28-10:00

Nine twenty-eight to ten o'clock

10:20~11:20

Ten twenty to eleven twenty

06:00~08:00

Six o'clock to eight o'clock

10:20 a.m.~13:30 p.m.

Ten twenty a.m. to thirteen thirty p.m.

Time abbreviations

5:00 am

Five o'clock sharp in the early morning

5:30 am

Half past five in the early morning

5:20:12 am

Five twenty and twelve seconds in the early morning

7:00 am

Seven o'clock sharp in the morning

7:30 AM

7:30 AM

7:20:12 a.m.

7:20:12 AM

07:08:12 A.M.

7:08:12 AM

5:00 pm

5:00 PM

5:30 PM

5:30 PM

5:20:12 p.m.

5:20:12 PM

05:09:12 P.M.

5:09:12 PM

9:00 pm

9:00 PM

9:30 pm

9:30 PM

9:20:12 PM

9:20:12 PM

9:02:12 P.M.

9:02:12 PM

12:00 pm

12:00 PM

12:30 p.m.

12:30 PM

12:20:12 PM

12:20:12 PM

English

Format

Examples

English output

Description

HH:MM AM or PM

09:00 AM

nine A M

HH indicates a one- or two-digit hour, MM indicates a two-digit minute, and AM/PM indicates morning/afternoon.

09:03 PM

nine oh three P M

09:13 p.m.

nine thirteen p m

HH:MM

21:00

twenty one hundred

HHMM

100

one oclock

time-time

8:00 am - 05:30 pm

eight a m to five p m

Common time formats and ranges are supported.

7:05~10:15 AM

seven oh five to ten fifteen A M

09:00-13:00

nine oclock to thirteen hundred

currency

Chinese

Format

Examples

Chinese output

Description

Number + currency identifier

12.00 RMB

12 RMB

Supported currencies include AUD (Australian dollar), CAD (Canadian dollar), HKD (Hong Kong dollar), JPY (Japanese yen), USD (US dollar), CHF (Swiss franc), NOK (Norwegian krone), SEK (Swedish krona), GBP (British pound), RMB (renminbi), CNY (yuan), and EUR (euro). Supported number formats include: integers, decimals, and international notation separated by commas.

12.50 RMB

12.50 RMB

12,000,000 RMB

12,000,000 RMB

12,000,000.00 RMB

12,000,000 RMB

12,000.35 RMB

12,000.35 RMB

Currency identifier + number

$12

12 USD

Supported: CAD (Canadian dollar), $ (US dollar), Fr (franc), kr (Danish krone), £ (British pound), ¥ (yuan), and € (euro). Supported number formats include: integers, decimals, and international notation separated by commas.

$12.00

12 USD

$12.12

2.12 USD

$12,000

12,000 USD

$12,000.00

12,000 USD

$12,000.99

12,000.99 USD

Other default readings

1213

one thousand two hundred and thirteen

None

1213 KML

one thousand two hundred and thirteen K M L

1213.00 KML

one thousand two hundred and thirteen K M L

1213.9 KML

one thousand two hundred and thirteen point nine K M L

1,000 KML

one thousand K M L

1,000.00 KML

one thousand K M L

1,000.98 KML

one thousand point nine eight K M L

12,000

twelve thousand

English

Format

Examples

English output

Description

Number + currency symbol

1.00 RMB

one yuan

Supported number formats: integers, decimals, and the international notation with comma separators.

Supported currency symbols:

CN¥ (yuan)

CNY (yuan)

RMB (yuan)

AUD (australian dollar)

CAD (canadian dollar)

CHF (swiss franc)

DKK (danish krone)

EUR (euro)

GBP (british pound)

HKD (Hong Kong(China) dollar)

JPY (japanese yen)

NOK (norwegian krone)

SEK (swedish krona)

SGD (singapore dollar)

USD (united states dollar)

2.02 CNY

two point zero two yuan

1,000.23 CN¥

one thousand point two three yuan

1.01 SGD

one singapore dollar and one cent

2.01 CAD

two canadian dollars and one cent

3.1 HKD

three hong kong dollars and ten cents

1,000.00 EUR

one thousand euros

Currency symbol + number

US$ 1.00

one US dollar

Supported number formats: integers, decimals, and the international notation with comma separators.

Supported currency symbols:

US$ (US dollar)

CA$ (Canadian dollar)

AU$ (Australian dollar)

SG$ (Singapore dollar)

HK$ (Hong Kong dollar)

C$ (Canadian dollar)

A$ (Australian dollar)

$ (dollar)

£ (pound)

€ (euro)

CN¥ (yuan)

CNY (yuan)

RMB (yuan)

AUD (australian dollar)

CAD (canadian dollar)

CHF (swiss franc)

DKK (danish krone)

EUR (euro)

GBP (british pound)

HKD (Hong Kong(China) dollar)

JPY (japanese yen)

NOK (norwegian krone)

SEK (swedish krona)

SGD (singapore dollar)

USD (united states dollar)

$0.01

one cent

JPY 1.01

one japanese yen and one sen

£1.1

one pound and ten pence

€2.01

two euros and one cent

USD 1,000

one thousand united states dollars

Number + quantifier + currency symbol

Or

Currency symbol + number + quantifier

1.23 Tn RMB

one point two three trillion yuan

Supported quantifier formats include:

thousand

million

billion

trillion

Mil (million)

mil (million)

Bil (billion)

bil (billion)

MM (million)

Bn (billion)

bn (billion)

Tn (trillion)

tn (trillion)

K(thousand)

k (thousand)

M (million)

m (million)

$1.2 K

one point two thousand dollars

measure

Chinese

Format

Examples

Chinese output

Description

Number + Chinese unit

2 pieces

two pieces

Common Chinese units and unit abbreviations are supported.

120 hectares

one hundred and twenty hectares

more than 100 milligrams

more than one hundred milligrams

approximately 100 meters

approximately one hundred meters

over 100 people

over one hundred people

1 centimeter 20 millimeters

one centimeter twenty millimeters

120.00 square kilometers

one hundred and twenty square kilometers

Number + unit abbreviation

120.56 cm²

one hundred twenty point five six square centimeters

120 ㎡ 56 cm²

one hundred twenty square meters fifty-six square centimeters

100 m 12 cm 6 mm

one hundred meters twelve centimeters six millimeters

Range

10~15 kg

ten to fifteen kilograms

10.24~789.82 mu

ten point two four to seven hundred eighty-nine point eight two mu

10 m~15 m

ten meters to fifteen meters

10.24 cm~19.08 cm

ten point two four centimeters to nineteen point zero eight centimeters

number + unit + "/" + unit

10 CNY/jin

ten CNY per jin

199~299 CNY/piece

one hundred ninety-nine to two hundred ninety-nine CNY per piece

299.99 CNY/g~399.99 CNY/g

two hundred ninety-nine point nine nine CNY per gram to three hundred ninety-nine point nine nine CNY per gram

Other default readings

12 bundles

twelve bundles

30 rm

thirty r m

four hundred million compatriots

four hundred million compatriots

12.897 micrograms

twelve point eight nine seven micrograms

English

Format

Examples

English output

Description

number + unit of measurement

1.0 kg

one kilogram

Supported number formats: integers, decimals, and the international notation with comma separators.

Common unit abbreviations are supported.

1,234.01 km

one thousand two hundred thirty four point zero one kilometres.

Unit of measurement

mm2

square millimetre

Common symbols

SymbolChinese readingEnglish pronunciation
!Exclamation markexclamation mark
“Double quotedouble quote
#Hash signpound
$dollardollar
%Percent signpercent
&andand
‘Single quoteleft quote
(Left parenthesisleft parenthesis
)Right parenthesisright parenthesis
*Asteriskasterisk
+Plus signplus
,Commacomma
-Hyphendash
.Pointdot
/Slashslash
:Zero colonsolon
;Semicolonsemicolon
<Less thanless than
=Equals signequals
>Greater thangreater than
?Question markquestion mark
@atat
[Left square bracketleft bracket
\Backslashback slash
]Right square bracketright bracket
^Caretcaret
_Underscoreunderscore
`Backtickback quote
{Left curly braceleft brace
|VERTICAL LINEvertical bar
}Right curly braceright brace
~Tildetilde
!Exclamation markexclamation mark
“Left double quotation markleft double quote
”Right double quotation markright double qute
‘Left single quotation markleft quote
’Right single quotation markright quote
(Left parenthesisleft parenthesis
)Right parenthesisright parenthesis
,Commacomma
。Periodfull stop
—Hyphenem dash
:Coloncolon
;Semicolonsemicolon
?Question markquestion mark
、Enumeration commaenumeration comma
…ellipsisellipsis
……ellipsisellipsis
《Left title markleft guillemet
》Right title markright guillemet
¥RMB signyuan
≥Greater than or equal togreater than or equal to
≤Less than or equal toless than or equal to
≠Not equal tonot equal
≈Approximately equal toapproximately equal
±Plus-minusplus or minus
×Multiplication signtimes
πPipi
ΑAlphaalpha
ΒBetabeta
ΓGammagamma
ΔDeltadelta
ΕEpsilonepsilon
ΖZetazeta
ΘThetatheta
ΙIotaiota
ΚKappakappa
∧Lambdalambda
ΜMumu
ΝNunu
ΞXiksi
ΟOmicronomicron
∏Pipi
ΡRhorho
∑Sigmasigma
ΤTautau
ΥUpsilonupsilon
Φfaiphi
ΧChichi
ΨPsipsi
ΩOmegaomega
αAlphaalpha
βBetabeta
γGammagamma
δDeltadelta
εEpsilonepsilon
ζZetazeta
ηEtaeta
θThetatheta
ιIotaiota
κKappakappa
λLambdalambda
μMumu
νNunu
ξXiksi
οOmicronomicron
πPipi
ρRhorho
σSigmasigma
τTautau
υUpsilonupsilon
φfaiphi
χChichi
ψPsipsi
ωOmegaomega

Common measurement units

Format

Category

Chinese example

English example

Abbreviation

Length

nm (nanometer), μm (micrometer), mm (millimeter), cm (centimeter), m (meter), km (kilometer), ft (foot), in (inch)

nm (nanometre), μm (micrometre), mm (millimetre), cm (centimetre), m (metre), km (kilometre), ft (foot), in (inch)

Area

cm² (square centimeter), ㎡ (square meter), km² (square kilometer), SqFt (square foot)

cm² (square centimetre), ㎡ (square metre), km2 (square kilometre), SqFt (square foot)

Volume

cm³ (cubic centimeter), m³ (cubic meter), km³ (cubic kilometer), mL (milliliter), L (liter), gallon (gallon)

cm³ (cubic centimetre), m³ (cubic metre), km3 (cubic kilometre), mL (millilitre), L (millilitre), gal (gallon)

Weight

μg (microgram), mg (milligram), g (gram), kg (kilogram)

μg (microgram), mg (microgram), g (gram), kg (kilogram)

Time

min (minute), sec (second), ms (millisecond)

min (minute), sec (second), ms (millisecond)

Electromagnetism

μA (microampere), mA (milliampere), Ω (ohm), Hz (hertz), kHz (kilohertz), MHz (megahertz), GHz (gigahertz), V (volt), kV (kilovolt), kWh (kilowatt-hour)

μA (microamp), mA (milliamp), Hz (hertz), kHz (kilohertz), MHz (megahertz), GHz (gigahertz), V (volt), kV (kilovolt), kWh (kilowatt hour)

Sound

dB (decibel)

dB (decibel)

Air pressure

Pa (pascal), kPa (kilopascal), Mpa (megapascal)

Pa (pascal), kPa (kilopascal), MPa (megapascal)

Other common units

In addition to the categories listed above, Chinese units such as mi (meter), miao (second), meiyuan (US dollar), and haoshengmeiping (milliliter per bottle) are supported, as well as Chinese measure words such as jia (for aircraft), chang (for shows), tou (for animals), bu (for devices), and pen (for potted plants).

Units of measurement beyond the above categories are also supported, such as tsp (teaspoon), rpm (round per minute), KB (kilobyte), and mmHg (milimetre of mercury).

Examples

cardinal

<speak>
  <say-as interpret-as="cardinal">12345</say-as>
</speak>
<speak>
  <say-as interpret-as="cardinal">10234</say-as>
</speak>

digits

<speak>
  <say-as interpret-as="digits">12345</say-as>
</speak>
<speak>
  <say-as interpret-as="digits">10234</say-as>
</speak>

telephone

<speak>
  <say-as interpret-as="telephone">12345</say-as>
</speak>
<speak>
  <say-as interpret-as="telephone">10234</say-as>
</speak>

name

<speak>
  她的曾用名是<say-as interpret-as="name">曾小凡</say-as>
</speak>

address

<speak>
  <say-as interpret-as="address">富路国际1号楼3单元304</say-as>
</speak>

id

<speak>
  <say-as interpret-as="id">myid_1998</say-as>
</speak>

characters

<speak>
  <say-as interpret-as="characters">希腊字母αβ</say-as>
</speak>
<speak>
  <say-as interpret-as="characters">*b+3.c$=α</say-as>
</speak>

punctuation

<speak>
  <say-as interpret-as="punctuation"> -./:;</say-as>
</speak>

date

<speak>
  <say-as interpret-as="date">1000-10-10</say-as>
</speak>
<speak>
  <say-as interpret-as="date">10-01-2020</say-as>
</speak>

time

<speak>
  <say-as interpret-as="time">5:00am</say-as>
</speak>
<speak>
  <say-as interpret-as="time">0500</say-as>
</speak>

currency

<speak>
  <say-as interpret-as="currency">13,000,000.00RMB</say-as>
</speak>
<speak>
  <say-as interpret-as="currency">$1,000.01</say-as>
</speak>

measure

<speak>
  <say-as interpret-as="measure">100m12cm6mm</say-as>
</speak>
<speak>
  <say-as interpret-as="measure">1,000.01kg</say-as>
</speak>

Tag relationships

<say-as> tags can contain text.

LaTeX tags and symbols

View the supported tags and symbols by category. The formula input examples include delimiters; the reading column provides examples in Chinese.

Basic math

Tag or symbol

Meaning

Formula content example

Formula input example

Example reading

+

Plus sign

2 + 3 = 5

$2 + 3 = 5$

Two plus three equals five

-

Minus

3 - 2 = 1

$3 - 2 = 1$

Three minus two equals one

\pm

Plus-minus

\pm 1 \pm 2

$\pm 1\pm 2$

Plus or minus one, plus or minus two

Plus or minus

\times

Multiplication sign

2 \times 3 = 6

$2 \times 3 = 6$

Two times three equals six

×

2 × 3 = 6

$$2 × 3 = 6$$

*

2 * 3 = 6

\(2 * 3 = 6\)

\div

Divided by

6\div2=3

\[6\div2=3\]

Six divided by two equals three

÷

6÷2=3

$6÷2=3$

/

6/2=3

$6/2=3$

=

Equals

3+5=8

$3+5=8$

Three plus five equals eight

<

Less than

1< 2

$1< 2$

One is less than two

≤

Less than or equal to

3≤5

$3≤5$

Three is less than or equal to five

<=

3<=5

$3<=5$

\leq

3\leq5

$3\leq 5$

\le

3\le5

$3\le 5$

\leqq

3\leqq5

$3\leqq 5$

\leqslant

3\leqslant5

$3\leqslant 5$

>

Greater than

2>1

$2>1$

Two is greater than one

≥

Greater than or equal to

5≥3

$5≥3$

Five is greater than or equal to three

>=

5>=3

$5>=3$

\geq

5\geq3

$5\geq 3$

\ge

5\ge3

$5\ge 3$

\geqq

5\geqq3

$5\geqq 3$

\geqslant

5\geqslant3

$5\geqslant 3$

\frac

Fraction

2\frac3

$\frac {2}{3}$

Two thirds

^

Power

2^1

$2^{1}$

Two to the first power

\sqrt

Square root

\sqrt{9} = 3

$\sqrt {9} = 3$

The square root of nine equals three

\sqrt[3]{8} = 2

$\sqrt[3]{8} = 2$

The cube root of eight equals two

\%

Percentage

5\%

$5\%$

Five percent

|

Absolute value

∣3∣=3

$|3| =3$

The absolute value of three equals three

\vert

3\vert=3

$\vert 3\vert =3$

The absolute value of three, absolute value, equals three

\lg

Logarithm

lg {10}

$\lg {10}$

log ten

\log

Logarithm

\log{5}

$\log{5}$

log five

\ln

Natural logarithm

\lnX

$ln {10}$

LN ten

!

Factorial

5!

$5!$

The factorial of five

()

Parentheses

(2+1)

$(2+1)$

Two plus one inside the parentheses

\{ \}

$\{2+1\}$

Left curly brace, two plus one, right curly brace

Special mathematical symbols

Tag or symbol

Meaning

Formula content example

Formula input example

Example reading

\alpha

alpha

\alpha

$\alpha$

α

\Alpha

\Alpha

$\Alpha$

\beta

beta

\beta

$\beta$

β

\Beta

\Beta

$\Beta$

\gamma

gamma

\gamma

$\gamma$

γ

\Gamma

\Gamma

$\Gamma$

\delta

delta

\delta

$\delta$

Δ

\Delta

\Delta

$\Delta$

\infty

Infinity (Chinese)

\infty

$\infty$

Infinity

∞

infty (English)

∞

$∞$

Geometry

Tag or symbol

Meaning

Formula content example

Formula input example

Example reading

\pi

Pi

\pi=3.14159

$\pi =3.14159$

Pi equals three point one four one five nine

\sin (sine)

Trigonometric functions

\sin 30^\circ =\frac {1}{2}

$\sin 30^\circ =\frac {1}{2}$

The sine of thirty degrees equals one half

\cos (cosine)

\cos 45^\circ =\frac {\sqrt {2}}{2}

$\cos 45^\circ =\frac {\sqrt {2}}{2}$

The cosine of forty-five degrees equals the square root of two over two

\tan (tangent)

\tan 30^\circ =\frac {\sin 30^\circ}{\cos 30^\circ}

$\tan 30^\circ =\frac {\sin 30^\circ}{\cos 30^\circ}$

The tangent of thirty degrees equals the sine of thirty degrees over the cosine of thirty degrees

\csc (cosecant)

\csc A

$\csc A$

cosecant A

\sec (secant)

\sec A

$\sec A$

secant A

\cot (cotangent)

\cot A

$\cot A$

cotangent A

\angle

Angle

\angle AB

$\angle AB$

Angle A B

∠

∠AB

$∠AB$

^\circ

Degree

∠AB = 30^\circ

$∠AB = 30^\circ$

Angle A B equals thirty degrees

\odot

Circle

\odot

$\odot$

Circle

\overset\frown

Arc

\overset\frown {BC}

$\overset\frown {BC}$

Arc BC

\rm{Rt}

Right angle

\because \rm{Rt}\triangle ABC

$\because \rm{Rt}\triangle ABC$

Because right triangle ABC

\mathrm{Rt}

\therefore AB \perp BC

$\therefore AB \perp BC$

Therefore AB is perpendicular to BC

\triangle

Triangle

\triangleABC

$\triangle ABC$

Triangle ABC

△

△ABC

$△ABC$

\parallelogram

Parallelogram

\parallelogramABCD

$\parallelogram ABCD$

Parallelogram ABCD

\perp

Perpendicular

AB \perp BC

$AB \perp BC$

A B is perpendicular to B C

\bot

AB \bot BC

$AB \bot BC$

⊥

AB ⊥ BC

$AB ⊥ BC$

\parallel

Parallel

A\parallel B

$A\parallel B$

A is parallel to B

\equalparallel

Parallel and equal to

A\equalparallel B

$A\equalparallel B$

A is parallel and equal to B

\cong

Congruent

△ABC\cong△DEF

$△ABC\cong△DEF$

Triangle ABC is congruent to triangle DEF

Conditions

Tag or symbol

Meaning

Formula content example

Formula input example

Example reading

\implies

Implies

\implies 1+1=2

$\implies 1+1=2$

Implies that one plus one equals two

\iff

Equivalent

p\iffq

$p\iffq$

p is equivalent to q

\because

Because

\because a = b \therefore b=a

$\because a = b \therefore b=a$

Because a equals b, so b equals a

\therefore

Therefore

Units

Units must be wrapped in \unit, \quantity, \mathit, \mathrm, or \rm, for example \unit{cm}.

Tag or symbolMeaningFormula content exampleFormula input exampleExample reading
mmmillimeter5\quantity{mm}$5\quantity{mm}$five millimeters
cmcentimeter5\quantity{cm}$5\quantity{cm}$five centimeters
dmdecimeter5\quantity{dm}$5\quantity{dm}$five decimeters
mmeter5\quantity{m}$5\quantity{m}$five meters
kmkilometer5\quantity{km}$5\quantity{km}$five kilometers
ggram5\quantity{g}$5\quantity{g}$five grams
kgkilogram5\quantity{kg}$5\quantity{kg}$five kilograms
tton5\quantity{t}$5\quantity{t}$five tons
mm^2square millimeter5\quantity{mm^2}$5\quantity{mm^2}$five square millimeters
cm^2square centimeter5\quantity{cm^2}$5\quantity{cm^2}$five square centimeters
dm^2square decimeter5\quantity{dm^2}$5\quantity{dm^2}$five square decimeters
m^2square meter5\quantity{m^2}$5\quantity{m^2}$five square meters
km^2square kilometer5\quantity{km^2}$5\quantity{km^2}$five square kilometers
mm^3cubic millimeter5\quantity{mm^3}$5\quantity{mm^3}$five cubic millimeters
cm^3cubic centimeter5\quantity{cm^3}$5\quantity{cm^3}$five cubic centimeters
dm^3cubic decimeter5\quantity{dm^3}$5\quantity{dm^3}$five cubic decimeters
m^3cubic meter5\quantity{m^3}$5\quantity{m^3}$five cubic meters
km^3cubic kilometer5\quantity{km^3}$5\quantity{km^3}$five cubic kilometers
mlmilliliter5\quantity{ml}$5\quantity{ml}$five milliliters
ssecond5\quantity{s}$5\quantity{s}$five seconds
minminute5\quantity{min}$5\quantity{min}$five minutes
hhour5\quantity{h}$5\quantity{h}$five hours
km/hkilometers per hour5\quantity{km/h}$5\quantity{km/h}$five kilometers per hour
g/lgrams per liter5\quantity{g/l}$5\quantity{g/l}$five grams per liter

FAQ

What should I do if formulas are not read aloud correctly?

  1. Check whether the formula is wrapped in $...$, $$...$$, \(...\), or \[...\].
  2. Check whether the formula contains unsupported tags or symbols.
  3. Check whether the \ in the request string is correctly escaped as \\.

How do I handle backslashes in code?

For escaping instructions, see Usage. Formulas are written differently from code strings. For example, \frac should be written as \\frac in a regular string.