WeChat mini program

Updated at:

The Intelligent Speech Interaction SDK for WeChat mini programs converts text to speech and returns audio and task messages through callbacks. This topic describes SDK integration, a synthesis and playback example, and the main methods and parameters.

Prerequisites

  • Activate Intelligent Speech Interaction, create a project in the console, and obtain its Appkey.

  • Prepare a WeChat mini program project. In its backend, add the HTTPS domain of the application endpoint that provides tokens to the allowed request domains, and add wss://nls-gateway-cn-shanghai.aliyuncs.com to the allowed socket domains.

For the service protocol, supported voices, and audio parameters, see Speech synthesis API reference.

Download and install

Download the SDK from the GitHub repository, or download alibabacloud-nls-wx-sdk-master.zip. Copy the utils directory into the mini program project and import SpeechSynthesizer with require("../../utils/tts"). Adjust the relative path for the page location.

Obtain a token

Obtain NLS tokens on an application server and provide them to the mini program through an authenticated HTTPS endpoint. For instructions, see Obtain a token.

Keep the AccessKey ID and AccessKey secret on the server. Do not store them in mini program code or local storage. The server can cache tokens and refresh them before they expire to avoid requesting a new token for every call.

Code example

The example synthesizes input text into WAV audio and plays it after synthesis completes. It prevents duplicate tasks during synthesis and playback. Stopping a task or unloading the page closes the connection, destroys the player, and removes the temporary audio file for that task. The 60-second synthesis timeout is an application setting, not a service limit.

Replace APPKEY and TOKEN_URL and add the authentication required by the application server to getToken(). TOKEN_URL is an application endpoint, not an NLS OpenAPI endpoint. The example expects a token string and an expireTime Unix timestamp in seconds, with more than 60 seconds remaining before expiration.

Register pages/tts/tts in app.json. The following two files form the page.

pages/tts/tts.js

const SpeechSynthesizer = require("../../utils/tts");
const APPKEY = "YOUR_APPKEY";
const TOKEN_URL = "https://example.com/api/nls-token";
const URL = "wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1";
const SYNTHESIS_TIMEOUT_MS = 60000;
const fs = wx.getFileSystemManager();
let sequence = 0;

function getToken() {
  return new Promise((resolve, reject) => {
    wx.request({
      url: TOKEN_URL,
      method: "GET",
      timeout: 10000,
      // Add the authentication required by your application server.
      success(res) {
        const value = res.data;
        if (res.statusCode === 200 && value &&
            typeof value.token === "string" && value.token &&
            Number(value.expireTime) > Date.now() / 1000 + 60) {
          resolve(value.token);
        } else {
          reject(new Error("Unable to obtain a valid NLS token."));
        }
      },
      fail() { reject(new Error("Token request failed.")); }
    });
  });
}

Page({
  data: { text: "Hello, welcome to speech synthesis.", busy: false, error: "" },

  onLoad() {
    this.alive = true;
    this.task = null;
  },

  textInput(e) { this.setData({ text: e.detail.value }); },

  async onTtsStart() {
    if (!this.alive || this.task) return;
    const text = this.data.text.trim();
    if (!text) {
      this.setData({ error: "Enter text to synthesize." });
      return;
    }
    const task = {
      path: `${wx.env.USER_DATA_PATH}/tts-${Date.now()}-${++sequence}.wav`,
      phase: "token", bytes: 0, fileCreated: false, disposed: false
    };
    this.task = task;
    this.setData({ busy: true, error: "" });

    try {
      const token = await getToken();
      if (task.disposed) return;
      fs.writeFileSync(task.path, new ArrayBuffer(0));
      task.fileCreated = true;
      task.tts = new SpeechSynthesizer({ url: URL, appkey: APPKEY, token });
      task.phase = "synthesis";

      // Connection closure alone does not settle the SDK's start Promise.
      const interrupted = new Promise((resolve, reject) => {
        task.reject = reject;
        task.timer = setTimeout(() => {
          reject(new Error("Speech synthesis timed out."));
        }, SYNTHESIS_TIMEOUT_MS);
      });
      task.tts.on("data", data => {
        if (task.disposed) return;
        try {
          fs.appendFileSync(task.path, data);
          task.bytes += data.byteLength;
        } catch (_) {
          task.reject(new Error("Unable to save audio."));
        }
      });
      task.tts.on("completed", () => { task.phase = "complete"; });
      task.tts.on("closed", () => {
        if (!task.disposed && task.phase === "synthesis") {
          task.reject(new Error("Connection closed before synthesis completed."));
        }
      });
      task.tts.on("failed", message => {
        // Log only diagnostic fields, not credentials or the full response.
        try {
          const header = JSON.parse(message).header;
          console.error("Synthesis failed", header.status, header.task_id);
        } catch (_) { console.error("Synthesis failed"); }
      });

      const params = task.tts.defaultStartParams("aixia");
      params.text = text;
      params.format = "wav";
      await Promise.race([task.tts.start(params), interrupted]);
      clearTimeout(task.timer);
      if (task.disposed) return;
      if (!task.bytes) throw new Error("No audio was returned.");

      task.phase = "playback";
      const audio = wx.createInnerAudioContext();
      task.audio = audio;
      audio.onEnded(() => this.dispose(task));
      audio.onError(() => this.dispose(task, "Unable to play audio."));
      audio.src = task.path;
      audio.play();
    } catch (_) {
      if (!task.disposed) {
        this.dispose(task, "Synthesis failed. Check the token, network, and audio settings.");
      }
    }
  },

  dispose(task, error = "") {
    if (!task || task.disposed) return;
    task.disposed = true;
    clearTimeout(task.timer);
    if (task.reject) task.reject(new Error("Task cancelled."));
    if (task.tts) task.tts.shutdown();
    if (task.audio) {
      task.audio.stop();
      task.audio.destroy();
    }
    if (task.fileCreated) {
      fs.unlink({
        filePath: task.path,
        fail() { console.warn("Unable to remove the temporary audio file."); }
      });
    }
    if (this.task === task) {
      this.task = null;
      if (this.alive) this.setData({ busy: false, error });
    }
  },

  onStop() { this.dispose(this.task); },

  onUnload() {
    this.alive = false;
    this.dispose(this.task);
  }
});

pages/tts/tts.wxml

<view>
  <textarea bindinput="textInput" value="{{text}}" maxlength="300" disabled="{{busy}}" />
  <button bindtap="onTtsStart" disabled="{{busy}}">Synthesize and play</button>
  <button bindtap="onStop" disabled="{{!busy}}">Stop</button>
  <text>{{error}}</text>
</view>

API reference

SpeechSynthesizer

Create a speech synthesis object with new SpeechSynthesizer(config). The config Object contains the following required fields.

config fields

Field

Type

Description

url

String

The WebSocket endpoint. The SDK has no default. The example uses wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1.

token

String

A valid NLS token provided by the application server.

appkey

String

The Appkey of the Intelligent Speech Interaction project.

Synthesis parameters

start(param) accepts a synthesis parameter object created in either of the following ways. defaultStartParams(voice) does not include text, which must be set separately.

Parameter

Type

Required

Description

text

String

Yes

The UTF-8 text to synthesize, up to 300 characters.

voice

String

No

The voice. The service default is xiaoyun; defaultStartParams(voice) uses the supplied value. For supported voices, see Speech synthesis API reference.

format

String

No

The audio format: pcm, wav, or mp3. The SDK default parameter object specifies wav. If a custom object omits this field, the service defaults to pcm.

sample_rate

Integer

No

The sample rate in Hz. Default: 16000.

volume

Integer

No

The volume, from 0 to 100. Default: 50.

speech_rate

Integer

No

The speech rate, from -500 to 500. Default: 0. See the multiplier conversion below.

pitch_rate

Integer

No

The pitch, from -500 to 500. Default: 0.

enable_subtitle

Boolean

No

Whether to enable word-level timestamps. The SDK default is false. For details, see Timestamp feature.

To synthesize speech with a supported emotion, add an ssml-emotion tag to text. For supported voices and syntax, see SSML overview.

Speech rate multiplier conversion

A speech_rate of -500, 0, or 500 corresponds to 0.5, 1, or 2 times the default speed. The default varies by voice and is typically about four Chinese characters per second. For a multiplier below 1, calculate (1 - 1 / multiplier) / 0.002; for a multiplier above 1, use (1 - 1 / multiplier) / 0.001. Use an approximate integer result. For example, 0.8 times the default speed corresponds to -125, and 1.2 times corresponds to 166.

Use the default parameter object

The following code uses an existing tts instance. Its default parameter object specifies WAV, a sample rate of 16000, a volume of 50, a speech rate and pitch of 0, and enable_subtitle: false.

const params = tts.defaultStartParams("aixia");
params.text = "Hello, welcome to speech synthesis.";
params.enable_subtitle = true;

Use a custom parameter object

Specify the audio format explicitly so that the file type used for storage and playback matches the synthesized format.

const params = {
  text: "Hello, welcome to speech synthesis.",
  voice: "aixia",
  format: "wav",
  sample_rate: 16000,
  volume: 50,
  speech_rate: 0,
  pitch_rate: 0,
  enable_subtitle: true
};

on(which, handler)

Registers a local event callback. which is the event name (String), and handler is the callback (Function). Registering the same event again replaces the previous callback. Returns no value. All events pass one argument to the callback except closed, which passes none.

Event

Argument type

Description

meta

String

Subtitle metadata, returned when word-level timestamps are enabled and supported.

data

ArrayBuffer

A binary audio chunk. Use byteLength to obtain its size in bytes.

completed

String

The synthesis completion message.

closed

None

The connection has closed.

failed

String

A service task error message.

String messages contain JSON and can be parsed with JSON.parse.

async start(param)

Starts synthesis using param (Object) and returns audio and messages through registered callbacks. On SynthesisCompleted, the SDK closes the connection, triggers completed, and resolves the returned Promise with the completion message string. Connection setup failures and TaskFailed reject the Promise. TaskFailed also triggers failed.

Important

A connection closure does not by itself settle the Promise returned by start(). Handle closed events that occur before synthesis completes and set an application-side timeout. Clean up the connection, files, and page state on failure.

shutdown()

Closes the connection without waiting for synthesis to complete. Takes no arguments and returns no value. Call it when cancelling a task, handling an error, or unloading the page. The application must also settle its pending wait and clean up local resources.