Appearance
Microsoft Azure 文本转语音(TTS)工具库,基于 microsoft-cognitiveservices-speech-sdk 实现浏览器端文本切分、SSML 合成、音频解码和播放控制。
安装
bash
pnpm add @mingto/microsoft-tts快速开始
typescript
import microsoftTts from '@mingto/microsoft-tts'
microsoftTts.config({
subscriptionKey: 'your-subscription-key',
})
const ttsInstance = microsoftTts.create({
region: 'eastasia',
voice_type: 'zh-CN-XiaoxiaoNeural',
})
ttsInstance
.on('audioFirstStart', () => {
console.log('音频首次播放')
})
.on('appError', (error) => {
console.error('应用错误', error)
})
.on('appFinish', () => {
console.log('应用已结束')
})
ttsInstance.start()
ttsInstance.send('你好呀。')
ttsInstance.end()API
microsoftTts.config(systemConfig)
配置 Azure 语音服务订阅密钥,返回当前模块对象,支持链式调用。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| subscriptionKey | string | 是 | Azure 语音服务订阅密钥 |
microsoftTts.create(businessParams?)
创建 TTS 控制器实例。
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| voice_type | string | zh-CN-XiaoxiaoNeural | 语音名称 |
| region | string | eastasia | Azure 语音服务区域 |
| volume | number | 100 | 音量,范围 0.0-100.0 |
| outputFormat | SpeechSynthesisOutputFormat | Raw24Khz16BitMonoPcm | 音频输出格式 |
| language | string | zh-CN | SSML 语言区域 |
实例方法
| 方法 | 说明 |
|---|---|
| start() | 激活应用,准备接收文本 |
| send(text) | 发送文本进行合成;仅在执行中生效 |
| end() | 通知文本输入结束,不会立即停止剩余音频播放 |
| finish() | 停止所有处理器并重置状态 |
| mute() | 静音当前音频输出 |
| unmute() | 恢复音频输出 |
| on(eventName, callback) | 订阅应用事件,返回当前实例 |
应用事件
| 事件名 | 说明 |
|---|---|
| audioFirstStart | 音频首次播放时触发 |
| appError | 应用发生错误时触发 |
| appFinish | 应用结束或销毁时触发 |
流式文本示例
typescript
const ttsInstance = microsoftTts.create({
region: 'eastasia',
voice_type: 'zh-CN-XiaoxiaoNeural',
})
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)常用中文音色
| 音色 | 说明 |
|---|---|
| zh-CN-XiaoxiaoNeural | 晓晓,女声 |
| zh-CN-YunxiNeural | 云希,男声 |
| zh-CN-YunyangNeural | 云扬,男声 |
| zh-HK-HiuMaanNeural | 香港粤语女声 |
| zh-TW-HsiaoChenNeural | 台湾女声 |
注意事项
subscriptionKey来自 Azure 语音服务资源。region是业务参数,默认eastasia;如果语音资源位于其他区域,请在create()中传入对应区域。- 前端代码中不建议直接暴露订阅密钥,生产环境建议通过服务端下发临时配置或代理请求。