2016-11-17 78 views
3

我试图从http请求中得到一个数组缓冲区,这个请求明确地说是一个数组缓冲区。然而,我没有设法做到这一点,关于这个问题的文件是相当稀缺的。Http,你如何处理角度2中的非文本响应?

let headers = new Headers({'Content-Type': "audio/mpeg"}); 
let options = new RequestOptions({responseType: ResponseContentType.ArrayBuffer, headers: headers }); 
this.http.get("http://localhost:4200/piano/A4.mp3") 
     .subscribe((response)=> this.play(response)); 

但我无法设法从响应中获取数组缓冲区。控制台中的响应主体无法识别,因此我认为它必须是正确的格式。此外,响应的内容类型确实是“音频/ mpeg”。

编辑:这里是未来的读者

play(arrBf) { 
    this.audioContext.decodeAudioData(arrBf, (buffer) => { 
     let source = this.audioContext.createBufferSource(); 
     source.buffer = buffer;     
     source.connect(this.audioContext.destination);  
     source.start(0);       
    }); 
    } 

    loadSounds(){ 
    let options = new RequestOptions({responseType: ResponseContentType.ArrayBuffer}); 
    this.http.get("http://localhost:4200/assets/piano/A4.mp3", options) 
     .map(r => r.arrayBuffer()) 
     .subscribe((d)=> { this.play(d)}); 
    } 

,并定义构造函数或smtg音频方面的一些工作代码:

constructor(private http:Http) { 
    let AudioContext_ = AudioContext || webkitAudioContext; 
    this.audioContext = new AudioContext_(); 
    } 
+1

你尝试没有括号'新的Blob(response.blob(),{type:'audio/mpeg'})'? – PierreDuc

+0

但是如果你做了response.blob(),你为什么要把它放在一个新的Blob调用中?也许你可以使用'response.arrayBuffer()'来启动blob – PierreDuc

+0

让我把它制作成答案:) – PierreDuc

回答

0

这里是未来的读者

play(arrBf) { 
    this.audioContext.decodeAudioData(arrBf, (buffer) => { 
     let source = this.audioContext.createBufferSource(); 
     source.buffer = buffer;     
     source.connect(this.audioContext.destination);  
     source.start(0);       
    }); 
    } 

    loadSounds(){ 
    let options = new RequestOptions({responseType: ResponseContentType.ArrayBuffer}); 
    this.http.get("http://localhost:4200/assets/piano/A4.mp3", options) 
     .map(r => r.arrayBuffer()) 
     .subscribe((d)=> { this.play(d)}); 
    } 

,并定义构造函数或smtg音频方面的一些工作代码:

constructor(private http:Http) { 
    let AudioContext_ = AudioContext || webkitAudioContext; 
    this.audioContext = new AudioContext_(); 
    } 
1

要从Response对象获得Blob Angular2你可以使用arrayBuffer()方法:

let blob: Blob = new Blob([response.arrayBuffer()], {type: 'audio/mpeg'}); 
从角

文件还没有更新,虽然

+0

正如我在上面回答你'response.arrayBuffer();'诀窍将响应转换到数组缓冲区是啊。在我的具体情况下,实际上并不需要转换为blob。不幸的是,由于某些原因无法解码数据,我仍然无法播放声音。但这是我想要的另一个问题:) – Ced