2016-04-20 13 views
2

我有一台服务器将ogg编码的音频提供给客户端,该客户端使用http GET请求该音频。 如果我注入了GET路线到它接收到的音频并在HTML音讯源:播放HTML音频标记的二进制字符串

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(); 

}; 

响应的日志显示有一个二进制字符串JSON在“数据”键:

Object {data: "OggS�1�/ڂ OpusHead��]OggS…�xs���������������������������������", status: 200, config: Object, statusText: "OK"} 

有没有办法来解码HTTP GET响应INT o我可以注入音频src?

+1

我不知道角度,但与XMLHttpRequest,哟你可以将'.responseType'设置为'“blob”,然后从这个blob响应中创建一个'objectURL'('URL.createObjectURL(this.response)'),你可以通过'src'您的音频元素。否则,如果您的目标浏览器确实支持AudioContextAPI,则可以使用['AudioContext.decodeAudioData()'](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/decodeAudioData)方法。 – Kaiido

+0

谢谢,你的回答帮了我很多。 – trahloff

回答

0

我终于成功地做了评论此结合它与此代码:

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(); 
    }) 
}; 
+1

你从哪里获取响应处理代码中的音频变量? –

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的