Python SDK

Updated at:

Use the Python SDK to submit text once and receive synthesized CosyVoice speech as an audio stream. SSML input is supported.

Prerequisites

Install the SDK

Obtain the SDK from GitHub or download streamInputTts-github-python. Extract the package, then run the following commands from the SDK root directory:

python -m pip install -r requirements.txt
python -m pip install .

After installation, import the SDK with import nls.

Usage notes

  • Create an NlsStreamInputTtsSynthesizer object for each synthesis task, and configure its callbacks in the constructor.

  • Configure the voice, audio format, and other request settings when starting the task.

  • Call startTts with the complete text, and then call waitForComplete.

  • The ending method sends the end-of-input notification, waits for synthesis to end, and closes the connection. Use shutdown() to close the connection immediately when aborting a task.

For supported voices, audio formats, and service limits, see Long-text-to-speech API.

Code examples

Set the project Appkey and NLS token in the NLS_APPKEY and NLS_TOKEN environment variables. Choose an example based on how the audio will be used.

Save audio

The example saves the synthesized audio to output.wav. No audio output device or PyAudio is required.

import json
import os
from contextlib import ExitStack

import nls

def main():
    appkey = os.environ["NLS_APPKEY"]
    token = os.environ["NLS_TOKEN"]
    result = {"completed": False, "error": None}

    with ExitStack() as stack:
        audio = stack.enter_context(open("output.wav", "wb"))

        def on_data(data, *args):
            try:
                audio.write(data)
            except Exception as error:
                result["error"] = error

        def on_sentence(message, *args):
            subtitles = json.loads(message).get("payload", {}).get("subtitles")
            if subtitles:
                print(json.dumps(subtitles, ensure_ascii=False))

        def on_completed(message, *args):
            result["completed"] = True
            task_id = json.loads(message)["header"]["task_id"]
            print("Synthesis completed. taskId=" + task_id)

        def on_error(message, *args):
            result["error"] = RuntimeError(message)

        settings = {
            "voice": "longxiaochun_v2",
            "aformat": "wav",
            "sample_rate": 24000,
        }
        sdk = nls.NlsStreamInputTtsSynthesizer(
            url="wss://nls-gateway-cn-beijing.aliyuncs.com/ws/v1",
            token=token,
            appkey=appkey,
            on_data=on_data,
            on_sentence_synthesis=on_sentence,
            on_sentence_end=on_sentence,
            on_completed=on_completed,
            on_error=on_error,
        )
        stack.callback(sdk.shutdown)

        try:
            sdk.startTts('<speak>Hello. Welcome to speech synthesis.</speak>', **settings)
            sdk.waitForComplete()
        except Exception:
            if result["error"] is not None:
                raise result["error"]
            raise

        if result["error"] is not None:
            raise result["error"]
        if not result["completed"]:
            raise RuntimeError("Connection closed before synthesis completed")

if __name__ == "__main__":
    main()

Play audio in real time

The runtime must have an available audio output device and PyAudio. The example plays 24 kHz, 16-bit, mono PCM audio.

Platform

Preparation

macOS

Run brew install portaudio, then python -m pip install pyaudio.

Debian / Ubuntu

Install the system package with sudo apt-get install python3-pyaudio.

CentOS

Run sudo yum install -y portaudio portaudio-devel, then python -m pip install pyaudio.

Windows

Run python -m pip install pyaudio.

import json
import os
from contextlib import ExitStack

import nls
import pyaudio

def main():
    appkey = os.environ["NLS_APPKEY"]
    token = os.environ["NLS_TOKEN"]
    result = {"completed": False, "error": None}

    with ExitStack() as stack:
        player = pyaudio.PyAudio()
        stack.callback(player.terminate)
        audio = player.open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)
        stack.callback(audio.close)
        stack.callback(audio.stop_stream)

        def on_data(data, *args):
            try:
                audio.write(data)
            except Exception as error:
                result["error"] = error

        def on_sentence(message, *args):
            subtitles = json.loads(message).get("payload", {}).get("subtitles")
            if subtitles:
                print(json.dumps(subtitles, ensure_ascii=False))

        def on_completed(message, *args):
            result["completed"] = True
            task_id = json.loads(message)["header"]["task_id"]
            print("Synthesis completed. taskId=" + task_id)

        def on_error(message, *args):
            result["error"] = RuntimeError(message)

        settings = {
            "voice": "longxiaochun_v2",
            "aformat": "pcm",
            "sample_rate": 24000,
        }
        sdk = nls.NlsStreamInputTtsSynthesizer(
            url="wss://nls-gateway-cn-beijing.aliyuncs.com/ws/v1",
            token=token,
            appkey=appkey,
            on_data=on_data,
            on_sentence_synthesis=on_sentence,
            on_sentence_end=on_sentence,
            on_completed=on_completed,
            on_error=on_error,
        )
        stack.callback(sdk.shutdown)

        try:
            sdk.startTts('<speak>Hello. Welcome to speech synthesis.</speak>', **settings)
            sdk.waitForComplete()
        except Exception:
            if result["error"] is not None:
                raise result["error"]
            raise

        if result["error"] is not None:
            raise result["error"]
        if not result["completed"]:
            raise RuntimeError("Connection closed before synthesis completed")

if __name__ == "__main__":
    main()

SDK reference

Task methods

Create a task with nls.NlsStreamInputTtsSynthesizer(url=..., token=..., appkey=..., ...). Set the service URL, NLS token, project Appkey, and callbacks in the constructor.

Method

Description

startTts(text, ...)

Starts synthesis and sends the complete text once. This method enables SSML.

waitForComplete()

Sends the end-of-input notification, blocks while waiting for synthesis to end, and closes the connection.

shutdown()

Closes the connection immediately.

get_last_task_id()

Gets the task ID.

Request parameters

The following parameters are accepted by startTts.

Name

Type

Description

text (required)

str

Complete UTF-8 text or SSML text to synthesize.

voice (optional)

str

Voice name. Default: longxiaochun.

aformat (optional)

str

Audio format: pcm, wav, mp3, or opus. Default: pcm.

sample_rate (optional)

int

Sample rate in Hz. Default: 24000. The SDK accepts 8000, 11025, 16000, 22050, 24000, 32000, 44100, and 48000; select a value supported by the voice.

volume (optional)

int

Volume from 0 to 100. Default: 50.

speech_rate (optional)

int

Speech rate from -500 to 500. Default: 0.

pitch_rate (optional)

int

Pitch from -500 to 500. Default: 0.

bit_rate (optional)

int

Bitrate in kbit/s for OPUS. Default: None, which leaves the bitrate to the service default.

ex (optional)

dict

Additional parameters merged into the request payload, such as AIGC metadata parameters. Default: None.

Callbacks

Configure callback functions and the optional callback_args list in the constructor. Elements in callback_args are passed to callbacks as *args.

Callback

Description

on_data(data, *args)

Receives binary audio data in the requested format.

on_sentence_begin(message, *args)

Receives a SentenceBegin event as a JSON string.

on_sentence_synthesis(message, *args)

Receives a SentenceSynthesis event as a JSON string, including incremental timestamps when supported and enabled.

on_sentence_end(message, *args)

Receives a SentenceEnd event as a JSON string, including sentence timestamps when supported and enabled.

on_completed(message, *args)

Receives a SynthesisCompleted event as a JSON string when the task completes.

on_error(message, *args)

Receives a server TaskFailed event as a JSON string.

on_close(*args)

Runs when the connection closes.

Optional settings

The snippets use the settings dictionary from the code examples. Apply request settings before starting synthesis. Use OPUS and AIGC settings with the Save audio example and change the output file extension to match the format. The real-time playback example uses PCM.

OPUS encoding

settings.update(aformat="opus", bit_rate=64)

Invisible AIGC metadata

Parameter

Type

Description

enable_aigc_tag

bool

Adds invisible AIGC metadata to WAV, MP3, or OPUS audio. Default: False.

aigc_propagator

str

Content propagator, stored in ContentPropagator. Defaults to the Alibaba Cloud UID. Applies when enable_aigc_tag is True.

aigc_propagate_id

str

Propagation identifier, stored in PropagateID. Defaults to the synthesis task ID. Applies when enable_aigc_tag is True.

settings["aformat"] = "wav"
settings.setdefault("ex", {}).update({
    "enable_aigc_tag": True,
    "aigc_propagator": "example-propagator",
    "aigc_propagate_id": "example-propagation-id",
})

Timestamps

Select a voice that supports timestamps and enable enable_subtitle. The examples receive subtitle data through on_sentence_synthesis and on_sentence_end.

settings["voice"] = "longxiaochun_v2"
settings.setdefault("ex", {}).update({"enable_subtitle": True})

SSML input

Select a voice that supports SSML. For supported voices and SSML usage, see Long-text-to-speech API.

startTts enables SSML. Pass the complete SSML text to this method:

sdk.startTts('<speak bgm="http://nls.alicdn.com/bgm/2.wav">How is the weather today?</speak>', **settings)
sdk.waitForComplete()

Error handling

Use try/except to handle exceptions raised by SDK calls, and handle task failures in on_error. Retain the task_id, status, and status_text from the error event for troubleshooting. For server status codes and solutions, see Error codes.