[英]How to play a base64 response from Google Text to Speech as an mp3 audio in browser using Javascript
I wrote this code to play an audio on a button click but I can't make it work.我编写了这段代码来在单击按钮时播放音频,但我无法让它工作。 Google docs aren't helpful on handling the response.
Google 文档对处理响应没有帮助。 Can anyone please help?
有人可以帮忙吗?
async function playVoiceover() {
const url ='https://texttospeech.googleapis.com/v1/text:synthesize?key=XXXXXXX'
const rawResponse = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'input':{
'ssml':`<speak>The <say-as interpret-as=\"characters\">SSML</say-as>
standard <break time=\"1s\"/>is defined by the
<sub alias=\"World Wide Web Consortium\">W3C</sub>.</speak>`
},
'voice':{
'languageCode':'en-us',
'name':'en-US-Standard-B',
'ssmlGender':'MALE'
},
'audioConfig':{
'audioEncoding':'MP3'
}
})
});
const content = await rawResponse.json();
const mp3 = 'data:audio/mp3;base64,'+window.atob(content.audioContent)
const audio = new Audio(mp3);
audio.play();
}
I'm leaving this answer as information about this case for the community:我将此答案作为有关此案例的信息留给社区:
window.atob()窗口.atob()
The atob() method decodes a base-64 encoded string. atob() 方法解码 base-64 编码的字符串。
texttospeech.googleapis.com (response structure) texttopeech.googleapis.com (响应结构)
{ "audioContent": string } // A base64-encoded string.
{ "audioContent": string } // 一个 base64 编码的字符串。
Its not needed to decoded when you are formating the mp3 string with the codec structure.当您使用编解码器结构格式化 mp3 字符串时,不需要对其进行解码。 You can see a similar response here .
您可以在此处看到类似的响应。
For additional details about the response from the texttospeech api:有关 texttospeech api 响应的其他详细信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.