NodeJS调用AWS Polly生成的MP3文件损坏无法播放求助
NodeJS调用AWS Polly生成的MP3文件无法播放的问题
使用NodeJS调用AWS Polly服务时,写入本地的.mp3文件无法播放,疑似损坏。打印audioBuffer看似正常,但找不到问题根源。
相关代码
const request: AWS.Polly.SynthesizeSpeechInput = { Text: textToSSMLResponse.ssml, TextType: 'ssml', OutputFormat: 'json', VoiceId: 'Matthew', Engine: "neural", SpeechMarkTypes: ["ssml"] }; const response = await client.synthesizeSpeech(request).promise(); const data = response.$response.data as AWS.Polly.SynthesizeSpeechOutput; const audioBuffer = data.AudioStream; fs.writeFileSync(`src/tmp/filename.mp3`, audioBuffer, 'binary');
打印的audioBuffer内容
Buffer 7b 22 74 69 6d 65 22 3a 37 30 33 37 2c 22 74 79 70 65 22 3a 22 73 73 6d 6c 22 2c 22 73 74 61 72 74 22 3a 31 35 34 2c 22 65 6e 64 22 3a 31 37 38 2c 22 ... 93 more bytes>
问题根源与解决方案
核心问题
你设置的OutputFormat: 'json'是错误的——这个参数指定Polly返回JSON格式的SpeechMarks标记数据,而非音频二进制流。从打印的Buffer开头{"time(对应十六进制7b 22 74 69 6d 65)就能看出,返回的是JSON结构,根本不是MP3音频。
修正步骤
- 修改OutputFormat为音频格式:将
OutputFormat改为'mp3'(或你需要的其他音频格式,比如pcm、ogg_vorbis)。 - 移除冲突参数:
SpeechMarkTypes参数要求OutputFormat必须是json或vtt,和音频格式冲突,所以如果不需要SpeechMarks,直接删掉这个参数;如果需要,要单独发起一次请求获取标记数据。
修正后的代码
const request: AWS.Polly.SynthesizeSpeechInput = { Text: textToSSMLResponse.ssml, TextType: 'ssml', OutputFormat: 'mp3', // 改为音频格式 VoiceId: 'Matthew', Engine: "neural" // 移除SpeechMarkTypes,避免和音频格式冲突 }; const response = await client.synthesizeSpeech(request).promise(); const data = response.$response.data as AWS.Polly.SynthesizeSpeechOutput; const audioBuffer = data.AudioStream; // 直接写入Buffer即可,无需指定'binary',Node.js会自动处理 fs.writeFileSync(`src/tmp/filename.mp3`, audioBuffer);
补充说明
- 如果需要同时获取音频和SpeechMarks,必须分两次调用Polly:
- 第一次请求音频:
OutputFormat: 'mp3',不带SpeechMarkTypes - 第二次请求标记:
OutputFormat: 'json',带上SpeechMarkTypes: ["ssml"]
- 第一次请求音频:
- MP3文件的头部通常是
ID3或FF FB等二进制标识,你之前的Buffer明显是JSON,这是判断问题的关键依据。
内容的提问来源于stack exchange,提问作者niclas_4
相关产品推荐
相关产品推荐

