如何在浏览器中使用Azure Speech Text-To-Speech服务
Azure Speech 服务浏览器端文本转语音(TTS)实现方案
前置准备
- 先在Azure门户创建Speech资源,获取对应的区域(region)和密钥(key)
- 引入官方浏览器端JS SDK:可通过npm安装
microsoft-cognitiveservices-speech-sdk包后引入对应浏览器适配版本,或下载官方浏览器端SDK到本地项目引入
最简实现代码
<!DOCTYPE html> <html> <body> <button id="speakBtn">点击播报文本</button> <script> // 替换为自有Azure Speech资源配置 const speechKey = "你的Azure Speech资源密钥"; const speechRegion = "你的资源所属区域"; document.getElementById("speakBtn").addEventListener("click", () => { // 初始化语音配置 const speechConfig = SpeechSDK.SpeechConfig.fromSubscription(speechKey, speechRegion); // 设置合成参数:输出语言、音色,可根据需求自行调整 speechConfig.speechSynthesisLanguage = "zh-CN"; speechConfig.speechSynthesisVoiceName = "zh-CN-XiaoxiaoNeural"; // 初始化合成器,默认使用设备扬声器输出 const synthesizer = new SpeechSDK.SpeechSynthesizer(speechConfig); const textToSpeak = "这是Azure Speech浏览器端文本转语音的测试内容"; synthesizer.speakTextAsync( textToSpeak, result => { if (result.reason === SpeechSDK.ResultReason.SynthesizingAudioCompleted) { console.log("语音合成完成"); } else { console.error("合成失败:", result.errorDetails); } synthesizer.close(); }, error => { console.error("调用出错:", error); synthesizer.close(); } ); }); </script> </body> </html>
注意事项
- 生产环境禁止在前端代码中明文硬编码Speech资源密钥,避免资源被盗用。可通过自有后端下发临时授权token,使用
SpeechSDK.SpeechConfig.fromAuthorizationToken(token, region)方法初始化配置 - 该实现完全运行在浏览器端,无需依赖Node.js环境,支持所有主流现代浏览器
- 若需获取合成后的音频流做自定义处理(如下载、自定义播放控制),可将合成器输出配置改为
AudioConfig.fromStreamOutput实现
内容的提问来源于stack exchange,提问作者NSS
相关产品推荐
相关产品推荐

