Node.js SDK

Updated at:

Use the Node.js SDK for speech synthesis to convert text to audio and receive audio data through event handlers. This topic provides installation instructions, a complete example, and reference information about connection settings, synthesis parameters, and events.

Prerequisites

  • Install Node.js 14 or later and npm, and configure the environment.

  • Obtain a project Appkey and an access token. For project configuration, see Manage projects. For token acquisition, see Obtain an access token.

  • Review the text requirements, voices, and service parameters in the Speech synthesis API.

Install the SDK

Install the SDK in your project directory:

npm install alibabacloud-nls

The complete example uses CommonJS. In an ES module project, use a named import:

import { SpeechSynthesizer } from "alibabacloud-nls";

Code example

This example uses alibabacloud-nls 1.0.4 to synthesize a short text once and save the audio as output.wav in the program's working directory. Before running the example, set NLS_APP_KEY and NLS_TOKEN in the runtime environment to your project Appkey and access token.

"use strict";

const fs = require("fs/promises");
const Nls = require("alibabacloud-nls");

async function main() {
  const appkey = process.env.NLS_APP_KEY;
  const token = process.env.NLS_TOKEN;
  if (!appkey || !token) {
    throw new Error("Set NLS_APP_KEY and NLS_TOKEN.");
  }
  const client = new Nls.SpeechSynthesizer({
    url: "wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1",
    appkey,
    token
  });
  const params = client.defaultStartParams("aixia");
  params.text = "Welcome to Intelligent Speech Interaction.";
  const chunks = [];
  let timer;
  let finished = false;

  client.on("data", (data) => chunks.push(data));
  client.on("meta", (message) => console.log("Subtitle:", message));
  client.on("completed", () => { finished = true; });

  try {
    await new Promise((resolve, reject) => {
      timer = setTimeout(() => reject(new Error("Synthesis timed out.")), 60000);
      client.on("failed", (message) => reject(new Error(message)));
      client.on("closed", () => {
        if (!finished) reject(new Error("Connection closed before completion."));
      });
      client.start(params, true, 6000).then(resolve, reject);
    });
    await fs.writeFile("output.wav", Buffer.concat(chunks));
    console.log("Saved output.wav");
  } finally {
    clearTimeout(timer);
    client.shutdown();
  }
}

main().catch((error) => {
  console.error(error.message || error);
  process.exitCode = 1;
});

Interfaces and parameters

SpeechSynthesizer

The SpeechSynthesizer class provides speech synthesis. Pass a connection configuration object to its constructor:

const client = new Nls.SpeechSynthesizer({ url, appkey, token });

Parameter

Type

Description

config

Object

The connection configuration object. The following fields are required.

config.url

String

The service URL, which must be explicitly set. The example uses wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1. For other endpoints, see Service endpoints.

config.appkey

String

The project Appkey.

config.token

String

The access token.

Synthesis parameters

Set the synthesis parameters before calling start(params).

Parameter

Type

Required

Description

text

String

Yes

The UTF-8 encoded text to synthesize, up to 300 characters. Use normal word spacing in English text.

voice

String

No

The voice. If omitted, the service uses xiaoyun. For available voices, see the voice list.

format

String

No

The audio format. Valid values: pcm, wav, and mp3. The service uses pcm if the field is omitted. The SDK's defaultStartParams() returns wav.

sample_rate

Integer

No

The audio sample rate. Default: 16,000 Hz.

volume

Integer

No

The volume. Valid values: 0 to 100. Default: 50.

speech_rate

Integer

No

The speech rate. Valid values: -500 to 500. Default: 0. The default speaking speed varies by voice.

pitch_rate

Integer

No

The pitch. Valid values: -500 to 500. Default: 0.

enable_subtitle

Boolean

No

Whether to enable word-level timestamps. Default: false. Use a voice that supports this feature. For details, see Timestamps.

Note

For a multi-emotion voice, use the SSML <emotion> tag in text to specify the emotion. The tag is supported only by multi-emotion voices. Synthesis fails if it is used with another voice. For syntax and usage, see the emotion tag.

Use either of the following approaches to prepare params for start(). Each snippet replaces the parameter configuration in the complete example.

Modify the default parameters

defaultStartParams(voice) returns the following object. voice is the supplied voice. If the argument is omitted, the field is undefined and is not sent in the request.

{
  voice: voice,
  format: "wav",
  sample_rate: 16000,
  volume: 50,
  speech_rate: 0,
  pitch_rate: 0,
  enable_subtitle: false
}

After obtaining the default object, change the fields as needed:

const params = client.defaultStartParams("aixia");
params.text = "Welcome to Intelligent Speech Interaction.";
params.speech_rate = 100;

Create a parameter object

const params = {
  text: "Welcome to Intelligent Speech Interaction.",
  voice: "aixia",
  format: "wav",
  sample_rate: 16000,
  volume: 50,
  speech_rate: 100,
  pitch_rate: 0,
  enable_subtitle: false
};

on(which, handler)

Registers an event handler. Returns no value. Register handlers before starting the task.

Parameter

Type

Description

which

String

The event name. See the following table.

handler

Function

The event handler.

Event

Description

Handler arguments

meta

Subtitle information. Enable enable_subtitle and use a supported voice.

One String argument.

data

An audio chunk.

One Buffer argument.

completed

Speech synthesis is complete.

One String argument.

closed

The connection is closed.

No arguments.

failed

The task failed. Provides error information.

One String argument.

String arguments contain JSON event data. The data event can occur multiple times. Preserve audio chunks in the order received. The complete example writes the chunks to a file after synthesis completes.

async start(param, enablePing, pingInterval)

Starts speech synthesis. Audio is delivered through data events. The returned Promise resolves with the completion event as a JSON string when completed occurs. Task errors and connection errors reject the Promise.

Parameter

Type

Description

param

Object

The synthesis parameters described earlier.

enablePing

Boolean

Whether to send Ping requests automatically. Defaults to false. Set to true to enable Ping.

pingInterval

Number

The Ping interval in milliseconds. If Ping is enabled and this value is omitted, the interval is 6,000.

shutdown()

Forcibly closes the connection. Takes no parameters and returns no value. Use it to release the connection when the call ends or exits with an error.