Google Text-to-Speech API生成音频无法播放问题求助(Apps Script)
Google Text-to-Speech API生成音频无法播放问题求助(Apps Script)
嘿,我来帮你捋捋这个问题!你遇到的音频存到Drive却无法播放的情况,主要是音频数据的编码和Blob类型不匹配,或者缺少必要的文件头导致的,咱们一步步来解决:
问题根源分析
LINEAR16编码的坑:
当你用LINEAR16编码时,API返回的是原始的PCM音频数据,但WAV格式不是单纯的PCM数据——它必须包含头部信息(比如采样率、声道数、比特率)才能被播放器识别。你直接把PCM数据存成.wav文件,播放器根本读不懂,自然无法播放。MP3编码的配置错误:
你说试过MP3编码但也不行,看你的代码应该是没同步修改Blob的MIME类型!API返回MP3二进制数据后,你还是用audio/wav作为MIME类型存文件,这就导致文件格式和后缀名不匹配,播放器识别失败。
修正后的代码方案
推荐直接用MP3编码,操作简单且兼容性好,下面是修正后的完整代码:
function textToSpeech() { // Set your API key here var apiKey = 'APIKEY'; // Create a new UrlFetchApp service. var urlFetchApp = UrlFetchApp; // Set the endpoint URL. var endpointUrl = 'https://texttospeech.googleapis.com/v1/text:synthesize?key=' + apiKey; // Create the request body. var requestBody = { 'input': { 'text': "This is the test" }, 'voice': { 'languageCode': 'en-US', 'name': 'en-US-Wavenet-B', 'ssmlGender': 'MALE' }, 'audioConfig': { 'audioEncoding': 'MP3', // 改成MP3编码 'speakingRate': 1.0, // 可选:调整语速 'pitch': 0.0 // 可选:调整音调 } }; // Make the request. var response = urlFetchApp.fetch(endpointUrl, { method: 'POST', contentType: 'application/json', payload: JSON.stringify(requestBody) }); // Get the audio data. var audioData = response.getContent(); // Save the audio data to a file. // 关键:MIME类型改成audio/mpeg,对应MP3格式 var audioBlob = Utilities.newBlob(audioData, 'audio/mpeg', 'output.mp3'); DriveApp.createFile(audioBlob); }
额外排查小技巧
- 确认你的API密钥已经启用了Google Text-to-Speech API,并且没有超出免费额度(可以去Google Cloud控制台查看)
- 存到Drive后,建议下载到本地再播放,有时候Drive的在线播放器可能有缓存或者格式识别延迟
- 如果一定要用WAV格式,需要手动给PCM数据添加WAV文件头,这个相对复杂,需要处理采样率(Wavenet语音默认是24000Hz)、声道数(单声道)等参数,如果你需要这种方案可以再告诉我!
备注:内容来源于stack exchange,提问作者vector




