Appearance
微信小程序端火山引擎文本转语音(TTS)控制器,支持流式文本输入、SSML 发音规则转换、音频缓存和小程序音频播放。
安装
bash
pnpm add @mingto/huoshan-mp-tts快速开始
typescript
import huoshanTts from '@mingto/huoshan-mp-tts'
huoshanTts.config({
ttsRequestBaseUrl: 'wss://audio.workbrain.cn/tts',
})
const ttsInstance = huoshanTts.create({
voice_type: 'zh_female_daimengchuanmei_moon_bigtts',
})
ttsInstance
.on('audioFirstStart', () => {
console.log('音频首次播放')
})
.on('appError', (error) => {
console.error('应用错误', error)
})
.on('appFinish', () => {
console.log('应用已结束')
})
ttsInstance.start()
ttsInstance.send('你好呀。')
ttsInstance.end()API
huoshanTts.config(systemConfig)
配置系统参数,返回当前模块对象,支持链式调用。
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| ttsRequestBaseUrl | string | wss://audio.workbrain.cn/tts | TTS WebSocket 请求地址 |
huoshanTts.create(businessParams?, ssmlConfig?)
创建小程序端 TTS 控制器实例。
typescript
const ttsInstance = huoshanTts.create(
{
voice_type: 'zh_female_daimengchuanmei_moon_bigtts',
text_type: 'ssml',
},
{
pronunciationRules: [
{
content: '筠连',
alphabet: 'py',
ph: 'jvn1 lian2',
},
],
}
)businessParams
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| voice_type | string | zh_female_daimengchuanmei_moon_bigtts | 音色类型 |
| text_type | plain / ssml | plain | 文本类型 |
| speed_ratio | number | 1 | 语速,约 [0.2, 3] |
| volume_ratio | number | 1 | 音量,约 [0.1, 3] |
| pitch_ratio | number | 1 | 音高,约 [0.1, 3] |
| language | string | cn | 语言代码 |
| provider | number | 0 | 供应商 ID |
| cache | boolean | false | 是否使用缓存 |
| stream | boolean | true | 是否流式返回 |
ssmlConfig
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| pronunciationRules | Array<{ content: string; alphabet: 'py' | 'ipa'; ph: string }> | [] | 发音规则,仅在 text_type: 'ssml' 时参与转换 |
实例方法
| 方法 | 说明 |
|---|---|
| start() | 激活应用,准备接收文本 |
| send(text) | 发送文本进行合成;仅在执行中生效 |
| end() | 通知文本输入结束,不会立即停止剩余音频播放 |
| finish() | 停止所有处理器并重置状态 |
| on(eventName, callback) | 订阅应用事件,返回当前实例 |
应用事件
| 事件名 | 说明 |
|---|---|
| audioFirstStart | 音频首次播放时触发 |
| appError | 应用发生错误时触发 |
| appFinish | 应用结束或销毁时触发 |
流式文本示例
typescript
const ttsInstance = huoshanTts.create({
voice_type: 'zh_female_daimengchuanmei_moon_bigtts',
})
const textList = ['你要抱', '抱我吗?', '我好', '喜欢你呀!']
let index = 0
ttsInstance.start()
const timer = setInterval(() => {
ttsInstance.send(textList[index])
index += 1
if (index === textList.length) {
ttsInstance.end()
clearInterval(timer)
}
}, 100)注意事项
- 该包面向微信小程序环境,依赖小程序原生音频能力进行播放。
config()需要传入系统配置对象;如不传入自定义地址,可使用默认ttsRequestBaseUrl。- 在页面离开或组件卸载时,建议调用
finish()停止播放并释放实例。