使用HTML音频标签播放二进制字符串

7
我有一个服务器,向使用http GET请求的客户端提供ogg编码音频。如果我将GET路由注入到HTML音频src中,它会接收音频并播放:
function working(text) {
    var downloadURL = 'http://localhost:8080/nlc/synthesize' +
        '?text=' + encodeURIComponent(text);

    audio.pause();
    audio.src = downloadURL;
    audio.play();

};

如果我使用http GET调用(在AngularJS中),并尝试将响应注入到HTML音频src中,它不会播放:
function not_working(text) {
  $http.get('http://localhost:8080/nlc/synthesize' + '?text=' + encodeURIComponent(text)).then(function(response) {
      console.log(response);
      audio.pause();
      audio.src = encodeURIComponent(response);
      audio.play();

};

响应日志显示,在“data”键中有一个二进制字符串的JSON:
Object {data: "OggS�1�/ڂ OpusHead��]OggS…�xs���������������������������������", status: 200, config: Object, statusText: "OK"}

有没有一种方法可以将http GET响应解码为我可以注入音频src中的内容?

1
我不了解Angular,但是使用XMLHttpRequest,您可以将其.responseType设置为"blob",然后从此Blob响应(URL.createObjectURL(this.response))创建一个objectURL,您将能够将其作为音频元素的src传递。否则,如果您的目标浏览器支持AudioContextAPI,则可以使用AudioContext.decodeAudioData()方法。 - Kaiido
谢谢,你的回答帮了我很多。 - trahloff
2个回答

4

我最终用这段代码实现了它:

function working(text) {
    var url = 'http://localhost:8080/nlc/synthesize';
    var req = {
        method: 'POST',
        url: url,
        responseType: 'blob',
        data: {
            "text": text
        },
        headers: {
            'Content-Type': 'application/json',
        }
    }

    $http(req).then(function(response) {
        console.log(response);
        audio.pause();
        audio.src = URL.createObjectURL(response.data);
        audio.play();
    })
};

3
响应处理代码中的音频变量来源是哪里? - Evan Burbidge

0

在 http.get 中,您可以传递一个带有可选配置的字典。

$http.get(Url, {
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});

https://docs.angularjs.org/api/ng/service/$http

也许你可以将这个与@kaiido的评论结合起来。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接