Я не могу воспроизводить звук при отправке запроса «AJAX» к моему API на стороне сервера.
У меня есть серверный код 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, а объект ошибки всегда равен нулю.
Может ли кто-нибудь объяснить, что я делаю неправильно и как это исправить? Мы будем очень признательны.
Спасибо.
ПРИМЕЧАНИЕ. Строка «тест» в URL-адресе становится текстовым параметром на бэкэнде и заканчивается в переменной параметров в SyntheAndRender.