如何使用 Angular $http 加载 AudioBuffer?

How do I load an AudioBuffer with Angular $http?

我开始使用 Web Audio Api 来尝试一下它,想看看如何在 AngularJS 中最好地使用它。

我尝试过的其他网络音频似乎在 Angular 中有效,例如创建网络音频正弦波等,但我不确定在 [=24= 中加载音频的最佳方式],如果我想用 Web Audio 来操作它 API

我天真地试图将一些功能直接放入 AngularJS 控制器中,这似乎不正确 - 代码如下。

在 Chrome Dev Tools Network 选项卡中,我可以看到应该加载的 test.mp3 通知 'Failed to load response data'。但是文件的路径是正确的,如果我在开发工具中单击它,文件将打开并开始播放。

非常感谢任何帮助

// Controller and attempt to load audio
(function () {
'use strict';

angular
    .module('app')
    .controller('mvMainCtrl', mvMainCtrl);

mvMainCtrl.$inject = ['$resource', '$scope', '$http' ];

function mvMainCtrl($scope, $http, $resource) {


var ctx; //audio context 
var buf; //audio buffer 

//init the sound system 
function init() { 
  console.log("in init"); 
try { 
    ctx = new AudioContext(); 
    loadFile(); 
} catch(e) { 
    alert('you need webaudio support'); 
} 
} 


function loadFile() { 
  var req = new XMLHttpRequest(); 
  req.open("GET","/app/main/sounds/test.mp3",true); 
req.responseType = "arraybuffer"; 
req.onload = function() { 
    //decode the loaded data 
    ctx.decodeAudioData(req.response, function(buffer) { 
        buf = buffer; 
        play(); 
    }); 
}; 
req.send(); 
}


  loadFile();


 function playback() {
    var playSound = ctx.createBufferSource();
    playSound.buffer = buf;
    playSound.connect(ctx.destination);
    playSound.start(audioContext.currentTime);
 }


  playback();



 }
})();

这是一个 BufferLoader 的实现,您可以使用它来加载一组声音文件:

// BufferLoader
function BufferLoader(context, urlList, callback) {
  this.context = context;
  this.urlList = urlList;
  this.onload = callback;
  this.bufferList = new Array();
  this.loadCount = 0;
}

BufferLoader.prototype.loadBuffer = function(url, index) {
  // Load buffer asynchronously
  var request = new XMLHttpRequest();
  request.open("GET", url, true);
  request.responseType = "arraybuffer";

  var loader = this;

  request.onload = function() {
    // Asynchronously decode the audio file data in request.response
    loader.context.decodeAudioData(
      request.response,
      function(buffer) {
        if (!buffer) {
          alert('error decoding file data: ' + url);
          return;
        }
        loader.bufferList[index] = buffer;
        if (++loader.loadCount == loader.urlList.length)
          loader.onload(loader.bufferList);
      },
      function(error) {
        console.error('decodeAudioData error', error);
      }
    );
  }

  request.onerror = function() {
    alert('BufferLoader: XHR error');
  }

  request.send();
}

BufferLoader.prototype.load = function() {
  for (var i = 0; i < this.urlList.length; ++i)
  this.loadBuffer(this.urlList[i], i);
}

如何使用它加载声音:

var sounds = ["assets/test.mp3", "test2.mp3"]
var context = window.AudioContext || window.webkitAudioContext || window.MozAudioContext || window.mozAudioContext;

var loader = new BufferLoader(context, sounds, onComplete);

var audioBuffers;
function onComplete(bufferList){
  console.log("Sounds loaded!");
  audioBuffers = bufferList;
}

function playSound(i){
  // create buffer source node which is used to play a sound one time
  var bufferSourceNode = context.createBufferSource(); 
  // set buffer to one of the loaded sounds;
  bufferSourceNode.buffer = audioBuffers[i];
  // connect to output
  bufferSourceNode.connect(context.destination);
  // play the sound
  bufferSourceNode.start()
}

现在要播放声音,您必须调用:

playSound(0); // play first sound in array of loaded sounds

在您的示例中,我看不到您在 decodeAudioData 中调用的 play() 函数的定义位置。您可能想调用 playback()。您还可以在尚未加载声音的控制器初始化时调用播放,这是您不应该做的。

我刚遇到同样的问题,在这个问题上花了几个小时后,我终于找到了解决问题的方法:

承诺风格:

$http({
    method: 'GET',
    url: url,
    responseType: 'arraybuffer'
}).then(function(response) {
    audioContext.decodeAudioData(response.data, function(buffer) {
        mainBuffer = buffer
    }, function(err) {
        console.log(err)
    })
})

标准样式:

$http({
    method: 'GET',
    url: url,
    responseType: 'arraybuffer'         
}).success(function(data) {
    audioContext.decodeAudioData(data, function(buffer) {
        mainBuffer = buffer
    }, function(err) {
        console.log(err)
    })
})

使用 XMLHttpRequest(),文件已损坏,responseType 属性应指定为 arraybuffer.