npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@amaster.ai/tts-client

v1.1.1

Published

Qwen TTS Realtime WebSocket client with audio playback

Readme

TTS Realtime WebSocket Client SDK

基于 WebSocket 的实时文本转语音(TTS)客户端 SDK,用于对接 qwen-tts 实时语音合成服务,支持流式音频返回与自动播放。


特性

  • 🔊 WebSocket 实时 TTS
  • 🎵 支持多种音频格式(pcm / mp3 / wav / opus
  • ▶️ 支持自动播放或手动播放
  • 📦 支持音频流分片回调
  • 🎧 浏览器原生 AudioContext 播放(PCM)
  • 🎭 多种音色可选

安装

# npm
npm install @amaster.ai/tts-client

# pnpm
pnpm add @amaster.ai/tts-client

# yarn
yarn add @amaster.ai/tts-client

快速开始

基础用法

import { createTTSClient } from "@amaster.ai/tts-client";

const tts = createTTSClient({
  voice: "Cherry",
  autoPlay: true,
  audioFormat: "pcm",
  sampleRate: 24000,
  onReady() {
    console.log("TTS 已就绪");
  },
  onAudioStart() {
    console.log("开始播放");
  },
  onAudioEnd() {
    console.log("播放结束");
  },
  onAudioChunk(chunks) {
    console.log("收到音频片段:", chunks.length);
  },
  onError(err) {
    console.error("TTS 错误:", err);
  },
});

// 建立连接
await tts.connect();

// 合成并播放语音
await tts.speak("你好,欢迎使用实时语音合成服务。");

// 关闭连接
// tts.close();

React 完整示例

import { useRef, useState } from "react";
import { createTTSClient, type TTSClient } from "@amaster.ai/tts-client";

const VoiceTypes = {
  Cherry: "Cherry - 甜美女声",
  Serena: "苏瑶 - 温柔小姐姐",
  Ethan: "晨煦 - 标准普通话",
  Chelsie: "千雪 - 二次元虚拟女友",
  Peter: "天津话",
};

function TTSPlayer() {
  const [voice, setVoice] = useState("Cherry");
  const [connected, setConnected] = useState(false);
  const [status, setStatus] = useState("disconnected");
  const [text, setText] = useState("你好,欢迎使用通义千问实时语音合成服务。");
  const clientRef = useRef<TTSClient | null>(null);

  const connectTTS = () => {
    if (clientRef.current) return;

    const ttsClient = createTTSClient({
      voice,
      autoPlay: true,
      audioFormat: "pcm",
      sampleRate: 24000,
      onReady: () => {
        setConnected(true);
        setStatus("connected");
      },
      onAudioStart: () => setStatus("playing"),
      onAudioEnd: () => setStatus("connected"),
      onAudioChunk: (chunks) => {
        console.log("音频片段数:", chunks.length);
      },
      onError: (err) => {
        console.error("TTS Error:", err);
        setStatus("error");
        setConnected(false);
      },
    });

    ttsClient.connect();
    clientRef.current = ttsClient;
  };

  const sendTTS = () => {
    if (!text || !clientRef.current) return;
    clientRef.current.speak(text);
  };

  const disconnectTTS = () => {
    clientRef.current?.close();
    clientRef.current = null;
    setConnected(false);
    setStatus("disconnected");
  };

  return (
    <div>
      <h3>🔊 实时语音合成(TTS)</h3>

      <div>状态: {status}</div>

      <div>
        <label>音色:</label>
        <select value={voice} onChange={(e) => setVoice(e.target.value)}>
          {Object.entries(VoiceTypes).map(([key, label]) => (
            <option key={key} value={key}>
              {label}
            </option>
          ))}
        </select>
      </div>

      <div>
        <label>合成文本:</label>
        <textarea rows={4} value={text} onChange={(e) => setText(e.target.value)} />
      </div>

      <div>
        <button onClick={connectTTS} disabled={connected}>
          1. 连接
        </button>
        <button onClick={sendTTS} disabled={!connected}>
          2. 合成语音
        </button>
        <button onClick={disconnectTTS} disabled={!connected}>
          断开
        </button>
      </div>
    </div>
  );
}

API 说明

createTTSClient(config)

创建一个 TTS 客户端实例。

TTSClientConfig

| 参数 | 类型 | 默认值 | 说明 | | ---------------- | ----------------------------------- | ---------- | ---------------------------------------------------------------------- | | voice | string | "Cherry" | 发音人名称,可选值:Cherry, Serena, Ethan, Chelsie, Peter 等 | | autoPlay | boolean | true | 是否在音频接收完成后自动播放 | | audioFormat | "pcm" \| "mp3" \| "wav" \| "opus" | "pcm" | 音频格式,注意:内置播放仅支持 pcm | | sampleRate | number | 24000 | 采样率 | | getAccessToken | () => string \| null | - | 获取访问令牌(用于 WebSocket 认证) | | onReady | () => void | - | 会话初始化完成回调 | | onAudioStart | () => void | - | 音频开始播放回调 | | onAudioEnd | () => void | - | 音频播放结束回调 | | onAudioChunk | (chunks: string[]) => void | - | 接收到音频分片回调 | | onError | (error: Error) => void | - | 错误回调 |

TTSClient

interface TTSClient {
  connect(): Promise<void>; // 建立 WebSocket 连接
  speak(text: string): Promise<void>; // 发送文本进行语音合成
  play(): void; // 手动播放(autoPlay=false 时使用)
  close(): void; // 关闭连接并释放资源
}

配合统一客户端使用

推荐与 @amaster.ai/client 统一客户端一起使用,自动处理认证:

import { createClient } from "@amaster.ai/client";

const client = createClient({
  baseURL: "https://api.amaster.ai",
});

const ttsClient = client.tts({
  voice: "Cherry",
  autoPlay: true,
  onReady() {
    console.log("TTS 已就绪");
  },
  onAudioStart() {
    console.log("开始播放");
  },
  onAudioEnd() {
    console.log("播放结束");
  },
});

await ttsClient.connect();
await ttsClient.speak("你好,欢迎使用 Amaster AI!");

音频说明

  • 当前内置播放逻辑 仅支持 pcm 格式
  • pcm 数据为 16-bit little-endian 单声道
  • 播放基于 AudioContext,仅支持浏览器环境
  • 若使用 mp3 / wav / opus,需自行实现解码与播放逻辑

运行环境

  • 浏览器(Chrome / Edge / Safari)
  • 需支持:
    • WebSocket
    • AudioContext
    • atob

注意事项

  • WebSocket 必须在 connect() 成功后才能调用 speak()
  • 多次 speak() 会覆盖之前的音频缓存
  • 自动播放依赖浏览器的自动播放策略,部分场景可能需要用户交互触发
  • 建议在组件卸载时调用 close() 释放资源

License

MIT