【发布时间】:2015-07-31 14:09:33
【问题描述】:
向我的服务器端 API 发出“AJAX”请求时,我无法播放音频。
我有后端 Node.js 代码,它使用 IBM 的 Watson Text-to-Speech 服务从文本中提供音频:
var render = function(request, response) {
var options = {
text: request.params.text,
voice: 'VoiceEnUsMichael',
accept: 'audio/ogg; codecs=opus'
};
synthesizeAndRender(options, request, response);
};
var synthesizeAndRender = function(options, request, response) {
var synthesizedSpeech = textToSpeech.synthesize(options);
synthesizedSpeech.on('response', function(eventResponse) {
if(request.params.text.download) {
var contentDisposition = 'attachment; filename=transcript.ogg';
eventResponse.headers['content-disposition'] = contentDisposition;
}
});
synthesizedSpeech.pipe(response);
};
我有客户端代码来处理:
var xhr = new XMLHttpRequest(),
audioContext = new AudioContext(),
source = audioContext.createBufferSource();
module.controllers.TextToSpeechController = {
fetch: function() {
xhr.onload = function() {
var playAudio = function(buffer) {
source.buffer = buffer;
source.connect(audioContext.destination);
source.start(0);
};
// TODO: Handle properly (exiquio)
// NOTE: error is being received
var handleError = function(error) {
console.log('An audio decoding error occurred');
}
audioContext
.decodeAudioData(xhr.response, playAudio, handleError);
};
xhr.onerror = function() { console.log('An error occurred'); };
var urlBase = 'http://localhost:3001/api/v1/text_to_speech/';
var url = [
urlBase,
'test',
].join('');
xhr.open('GET', encodeURI(url), true);
xhr.setRequestHeader('x-access-token', Application.token);
xhr.responseType = 'arraybuffer';
xhr.send();
}
}
后端返回我期望的音频,但我的成功方法 playAudio 从未被调用。相反,handleError 始终被调用,并且错误对象始终为 null。
谁能解释我做错了什么以及如何纠正这个问题?将不胜感激。
谢谢。
注意:URL 中的字符串“test”成为后端的文本参数,并最终出现在 synthesizeAndRender 中的 options 变量中。
【问题讨论】:
-
您确定支持音频格式吗?
-
我相信它一定是。我最初通过 url 直接使用相同的 Chrome 浏览器测试了相同的后端代码,它可以正常运行。
-
其实测试是在 Chromium 和 Gnu/Linux 上完成的。我相信它应该与我现在正在编写此代码的 OSX 中的 Chrome 相同,但我不确定。
-
更新:我在用于开发此代码的同一浏览器中运行了以下查询:localhost:3001/api/v1/text_to_speech/this%20is%20a%20test
标签: javascript node.js html5-audio text-to-speech ibm-watson