You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Text to Speech Node.js无法生成MP3文件问题求助

解决Azure Text to Speech Node.js代码不生成MP3文件的问题

我来帮你排查这个问题,先梳理下你代码里的几个关键错误,再解答你的疑问:

一、代码里的直接错误

你的代码有几处语法和引用问题,这是导致文件没生成的核心原因:

  • 未正确引入AudioConfig:AudioConfig是microsoft-cognitiveservices-speech-sdk包的一部分,你直接写AudioConfig.fromAudioFileOutput会导致找不到这个方法,必须加上sdk.前缀,写成sdk.AudioConfig.fromAudioFileOutput("speech.mp3")。
  • 语法错误:const synthesizer = new SpeechSynthesizer(speechConfig, audioConfig);F这行末尾多了个多余的F,会直接导致代码运行报错。
  • 未调用合成函数:你定义了synthesizeSpeech函数,但没有执行它,所以整个合成逻辑根本没启动。

二、关于是否需要fs模块的疑问

完全不需要额外使用fs服务写入文件。Azure Cognitive Services Speech SDK的AudioConfig.fromAudioFileOutput方法已经内置了文件写入逻辑,只要配置正确,SDK会自动把合成的音频写入你指定的文件路径。

三、Bing Speech与Azure Speech的差异

Bing Speech是微软已经淘汰的旧版语音服务,现在已经被Azure Cognitive Services Speech Service完全替代。两者的SDK架构、API调用方式完全不同,所以旧的Bing Speech示例代码不能直接套用到Azure TTS上,建议你专注于Azure官方的Speech SDK文档和示例进行开发。

修正后的完整可运行代码

const sdk = require("microsoft-cognitiveservices-speech-sdk");
var subscriptionKey = "809-myazureapikey";
var serviceRegion = "westeurope"; // e.g., "westus"

function synthesizeSpeech() {
  // 正确配置语音服务参数
  const speechConfig = sdk.SpeechConfig.fromSubscription(subscriptionKey, serviceRegion);
  // 正确指定输出音频文件
  const audioConfig = sdk.AudioConfig.fromAudioFileOutput("speech.mp3");
  
  // 初始化语音合成器
  const synthesizer = new sdk.SpeechSynthesizer(speechConfig, audioConfig);

  synthesizer.speakTextAsync(
    "A simple test to write to a file.",
    result => {
      if (result) {
        console.log("语音合成成功!结果信息:", JSON.stringify(result));
      }
      synthesizer.close();
    },
    error => {
      console.error("语音合成出错:", error);
      synthesizer.close();
    });
}

// 执行合成函数
synthesizeSpeech();

运行这段修正后的代码,只要你的订阅密钥和区域配置正确,就会在当前目录下生成speech.mp3文件。

内容的提问来源于stack exchange,提问作者sigur7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 06:33:11