实现移动端音频自动播放

422 阅读1分钟
//创建并且new一个AudioContext对象
  var AudioContext = window.AudioContext || window.webkitAudioContext;
  this.audioContext = new AudioContext();

  //播放的方法
  playAudio(buffer) {
      this.source = this.audioContext.createBufferSource();
      this.source.buffer = buffer;
      this.source.connect(this.audioContext.destination);
      this.source.start(0);
      this.source.loop = true;
    },
    //通过新建请求把音频转成播放所需的格式
    getBuffer(url) {
      return new Promise((reslove, reject) => {
        let that = this;
        var request = new XMLHttpRequest();
        // 请求一个MP3文件
        request.open("GET", url, true);
        // Web Audio API 固定为 "arraybuffer"
        request.responseType = "arraybuffer";
        // 加载完成后解码
        request.onload = function () {
          that.audioContext.decodeAudioData(
            request.response,
            function (buffer) {
              reslove(buffer);
            },
            function (err) {
              console.log(err);
              reject(err);
              // 这里写解码出错的处理(例如文件损坏、格式不对等)
            }
          );
        };
        // 发送这个XMLHttpRequest请求
        request.send();
      });
    },