Skip to content

讯飞文本转语音(TTS)服务工具库,基于讯飞开放平台 WebAPI 实现浏览器端文本切分、语音合成、转码、解码和播放控制。

安装

bash
pnpm add @mingto/xunfei-tts

快速开始

typescript
import xunfeiTTS from '@mingto/xunfei-tts'

xunfeiTTS.config({
  API_SECRET: 'your-api-secret',
  APPID: 'your-app-id',
  API_KEY: 'your-api-key',
})

const ttsInstance = xunfeiTTS.create({
  aue: 'lame',
  sfl: 1,
  vcn: 'xiaoyan',
  speed: 50,
  volume: 50,
  pitch: 50,
})

ttsInstance
  .on('audioFirstStart', () => {
    console.log('音频首次播放')
  })
  .on('appFinish', () => {
    console.log('应用已结束')
  })

ttsInstance.start()
ttsInstance.send('你好,欢迎使用讯飞语音合成。')
ttsInstance.end()

API

xunfeiTTS.config(systemConfig)

配置讯飞平台认证参数。调用 create() 前必须先调用 config()

参数类型必填说明
API_SECRETstring在讯飞开放平台申请的 API Secret
APPIDstring在讯飞开放平台申请的 APPID
API_KEYstring在讯飞开放平台申请的 API Key

xunfeiTTS.create(businessParams?)

创建 TTS 控制器实例。

businessParams

参数类型默认值说明
auestringraw音频编码格式
sfl11配合 aue: 'lame' 使用,开启流式返回
aufstringaudio/L16;rate=16000音频采样率
vcnstringxiaoyan发音人名称
speednumber50语速,范围 0-100
volumenumber50音量,范围 0-100
pitchnumber50音高,范围 0-100
bgs0 / 10背景音,0 无背景音,1 有背景音
tteunicode / UTF8UTF8文本编码格式
reg0 / 1 / 22英文发音方式
rdn0 / 1 / 2 / 30数字发音方式

aue 可选值

说明
raw未压缩 PCM
lameMP3,配合 sfl: 1 使用流式返回
speex-org-wb;7标准开源 speex,16k
speex-org-nb;7标准开源 speex,8k
speex;7讯飞定制 speex,8k
speex-wb;7讯飞定制 speex,16k

实例方法

方法说明
start()激活应用,准备接收文本
send(text)发送文本进行合成;仅在执行中生效
end()通知文本输入结束,不会立即停止剩余音频播放
finish()停止所有处理器并重置状态
mute()静音当前音频输出
unmute()恢复音频输出
on(eventName, callback)订阅应用事件,返回当前实例

应用事件

事件名说明
audioFirstStart音频首次播放时触发
appFinish应用结束或销毁时触发

流式文本示例

typescript
const ttsInstance = xunfeiTTS.create({
  aue: 'lame',
  sfl: 1,
  vcn: 'xiaoyan',
})

const textStream = ['今天天气真好,', '我想去公园散步,', '享受这美好的一天。']

let index = 0
ttsInstance.start()

const interval = setInterval(() => {
  if (index < textStream.length) {
    ttsInstance.send(textStream[index])
    index += 1
  }
  else {
    ttsInstance.end()
    clearInterval(interval)
  }
}, 500)

注意事项

  • 需要先在讯飞开放平台获取 APPID、API_KEY、API_SECRET。
  • 前端代码中不建议直接暴露密钥,生产环境建议通过服务端下发临时配置或代理请求。
  • 使用 MP3 流式返回时建议设置 aue: 'lame'sfl: 1
  • 在页面离开或组件卸载时,建议调用 finish() 停止播放并释放实例。