使用JavaScript中的XMLHttpRequest加载音频

时间:2018-01-17 20:34:39

标签: javascript xmlhttprequest web-audio-api

我正在学习Web Audio API。我在JavaScript中加载我的声音文件thourgh XMLHttpRequest时遇到问题。请帮助。这是我的代码

var source;

function start() {
  console.log("WELCOME!!");
  try{
    var actx = new AudioContext();
  }catch(e){
    console.log('WebAudio api is not supported!!');
  }

  source = actx.createBufferSource()

  var req  = new XMLHttpRequest();
  req.open('GET','src3.ogg',true);
  req.responseType='ArrayBuffer';

  req.onload = function(){
    var audioData = req.response;
    actx.decodeAudioData(audioData,function(buffer){
      source.buffer = buffer;
      source.connect(actx.destination);
      source.loop();
    },
    function(e){
      console.log('Error in decoding audio'+e.err);
    }

  );
  }
  req.send();
}

function play() {
  source.start(0);
}
function stop(){
  source.stop(0);
}

浏览器显示此错误:

XML Parsing Error: not well-formed
Location: file:///home/uzumaki/Web_Audio_Projects/src3.ogg
Line Number 1, Column 5:

在body标签的 onload 事件上调用 start()方法

1 个答案:

答案 0 :(得分:1)

替代

req.responseType = "arraybuffer";

req.responseType = "ArrayBuffer";
{p> .responseType未按XMLHttpResponse实例

转换为小写