2017-03-14 71 views
0

使用以下服务播放字节数组格式的音频文件(wav/mp3)。AngularJS - 解码字节数组和播放音频文件(Wav/MP3)

myAudioService.getAudioTone(userid).then(function (data) { 

     var context; // Audio context 
     var buf;  // Audio buffer 
     $window.AudioContext = $window.webkitAudioContext; 
     context = new AudioContext(); 

     $timeout(function() { 

     $scope.playByteArray = function(){ 

      var arrayBuffer = new ArrayBuffer(data.length); 
      var bufferView = new Uint8Array(arrayBuffer); 
      for (i = 0; i < data.length; i++) { 
       bufferView[i] = data[i]; 
      } 

      context.decodeAudioData(arrayBuffer, function(buffer) { 
       buf = buffer; 
       play(); 
      }); 
     } 

     $scope.play = function(audioBuffer){ 

      // Create a source node from the buffer 
      var source = context.createBufferSource(); 
      source.buffer = buf; 
      // Connect to the final output node (the speakers) 
      source.connect(context.destination); 
      // Play immediately 
      source.start(0); 

     }  


     if(data.length !== '' || data !== ''){ 
      $scope.playByteArray(); 
     } 
     }, 3000); 

}); 

函数被调用,但它会抛出异常。

Uncaught (in promise) DOMException: Unable to decode audio data

我如何运行在Chrome,FF和IE浏览器?

P.S.控制器中已经定义了$window$timeout

回答

0

根据错误消息arrayBuffer不包含您认为它包含的内容。您应该验证阵列中的字节与编码的wav/mp3文件相同。

+0

有没有一种方法来验证阵列中的字节是否与编码的wav/mp3文件相同? – Slimshadddyyy

+0

不知道,因为你没有显示数据来自何处。但你可以验证mp3/wav文件可以通过使用类似'fetch(url).then(response => {context.decodeAudioData(response);})来解码' –