Http,你如何处理角度2中的非文本响应?

时间:2016-11-17 15:46:27

标签: angular

我正在尝试从一个明确称为数组缓冲区的http请求中获取数组缓冲区。但是我没有设法做到这一点,关于这个问题的文档相当稀缺。

Gcm.php -> public function getOpenClient(....){  
$client->setApiKey($this->getParameter('apiKey'));

    $new_client = new \Zend\Http\Client(null, array(
                      'adapter' => 'Zend\Http\Client\Adapter\Socket',
                      'sslverifypeer' => false
                  )); 
    $client->setHttpClient($new_client);
    return $client;
}

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

修改:以下是未来读者的一些工作代码

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

并在构造函数或smtg中定义音频上下文:

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

2 个答案:

答案 0 :(得分:1)

要从Angular2中的Blob对象获取Response,您可以使用arrayBuffer()方法:

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

虽然

,但还没有更新angular的文档

答案 1 :(得分: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_();
  }