[英]How to play audio javascript
我有一个网站可以访问API,该API可以执行文本到语音转换,并返回mp3(或其他格式)。 这是发出请求并尝试播放音频的代码:
$.ajax({
url: 'https://westus.tts.speech.microsoft.com/cognitiveservices/v1',
type: 'post',
data: '<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="en-US"><voice name="Microsoft Server Speech Text to Speech Voice (en-US, JessaRUS)">Hello, world!</voice></speak>',
headers: {
'Content-Type': 'application/ssml+xml', 'X-Microsoft-OutputFormat': 'audio-16khz-64kbitrate-mono-mp3', 'User-Agent': 'Chat', 'Authorization': token
},
success: function (audio) {
console.log(audio);
new Audio(audio).play();
}
});
该请求返回的是一个包含许多奇怪字符和“ LAME3.99.5”的字符串,我不知道如何播放此mp3。 new Audio(audio).play();
不起作用,因为我没有文件名,而是原始文件。
一段时间以前,我使用iframe解决了完全相同的问题。 唯一的区别是,我使用IBM Cloud(之前称为Bluemix)来运行Node-RED实例,该实例又将IBM Watson用于文本到语音转换。
这是jQuery代码:
var audio = $('#audio');
//*** Button actions
$("#btnSpeak").on("click", function(e) {
e.preventDefault();
// Remove any existing iframe element
$("#iframeHost").html("");
// Set the location of Node-RED flow to use
var baseURL = "https://texasswedenodered.mybluemix.net/speak";
// Get text to convert to speech
var text = $("#text").val();
// Calculate the URL of speech file to insert into iframe
var url = baseURL+"?text=" + text;
// Create iframe element in memory
var iframe = $('<iframe id="audioframe" src="'+url+'" frameborder="1" width="10px" height="10px" style="display:none;"></iframe>');
$("#iframeHost").append(iframe);
});
这是iframe的HTML:
<div id="iframeHost"></div>
在纯JS中,您将获取数据,将其转换为base64,将其作为<source>
添加到您的<audio>
,然后就可以播放它。 例如( http://jsbin.com/xuvemuziko/edit?js,output ):
var url = "https://archive.org/download/testmp3testfile/mpthreetest.mp3";
let createAudioElement = data => {
// we need an <audio> and a <source> element, because that's how web audio works:
let audio = new Audio();
let source = document.createElement('source');
// we know this is an mp3, so use that
source.type = "audio/mpeg";
let base64 = btoa(String.fromCharCode(...new Uint8Array(data)));
source.src = `data:${source.type};base64,${base64}`;
audio.appendChild(source);
// And then we play it.
audio.play();
};
let handleMP3response = response => {
response
.arrayBuffer()
.then(createAudioElement);
};
fetch(url)
.then(handleMP3response)
.catch(e => console.error(e));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.