17

我一直在使用 Web Audio API,我正在尝试加载歌曲的多个部分并将它们附加到一个新的 ArrayBuffer 中,然后使用该 ArrayBuffer 将所有部分作为一首歌曲播放。在以下示例中,我使用相同的歌曲数据(这是一个小循环)而不是歌曲的不同部分。

问题是它仍然只播放一次而不是两次,我不知道为什么。

下载歌曲

function init() {

  /**
   * Appends two ArrayBuffers into a new one.
   * 
   * @param {ArrayBuffer} buffer1 The first buffer.
   * @param {ArrayBuffer} buffer2 The second buffer.
   */
  function appendBuffer(buffer1, buffer2) {
    var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
    tmp.set( new Uint8Array(buffer1), 0);
    tmp.set( new Uint8Array(buffer2), buffer1.byteLength);
    return tmp;
  }

  /**
   * Loads a song
   * 
   * @param {String} url The url of the song.
   */
  function loadSongWebAudioAPI(url) {
    var request = new XMLHttpRequest();
    var context = new webkitAudioContext();

    request.open('GET', url, true);
    request.responseType = 'arraybuffer';

    /**
     * Appends two ArrayBuffers into a new one.
     * 
     * @param {ArrayBuffer} data The ArrayBuffer that was loaded.
     */
    function play(data) {
      // Concatenate the two buffers into one.
      var a = appendBuffer(data, data);
      var buffer = a.buffer;
      var audioSource = context.createBufferSource();
      audioSource.connect(context.destination);

      //decode the loaded data
      context.decodeAudioData(buffer, function(buf) {
        console.log('The buffer', buf);
        audioSource.buffer = buf;
        audioSource.noteOn(0);
        audioSource.playbackRate.value = 1;
      });

    };

    // When the song is loaded asynchronously try to play it.
    request.onload = function() {
      play(request.response);
    }

    request.send();
  }


  loadSongWebAudioAPI('http://localhost:8282/loop.mp3');
}

window.addEventListener('load',init,false);
4

2 回答 2

23

您的代码中的问题是您正在复制 MP3 文件的另一个副本并将其附加到自身的末尾。该副本被解码器有效地忽略了 - 它不是原始缓冲区数据,它只是文件流中的随机虚假垃圾,跟随一个完美完整的 MP3 文件。

您需要做的是首先将音频数据解码到 AudioBuffer 中,然后将音频缓冲区一起附加到新的 AudioBuffer 中。这需要对您的代码进行一些重组。

你想要做的是:

var context = new webkitAudioContext();

function init() {

  /**
   * Appends two ArrayBuffers into a new one.
   * 
   * @param {ArrayBuffer} buffer1 The first buffer.
   * @param {ArrayBuffer} buffer2 The second buffer.
   */
  function appendBuffer(buffer1, buffer2) {
    var numberOfChannels = Math.min( buffer1.numberOfChannels, buffer2.numberOfChannels );
    var tmp = context.createBuffer( numberOfChannels, (buffer1.length + buffer2.length), buffer1.sampleRate );
    for (var i=0; i<numberOfChannels; i++) {
      var channel = tmp.getChannelData(i);
      channel.set( buffer1.getChannelData(i), 0);
      channel.set( buffer2.getChannelData(i), buffer1.length);
    }
    return tmp;
  }

  /**
   * Loads a song
   * 
   * @param {String} url The url of the song.
   */
  function loadSongWebAudioAPI(url) {
    var request = new XMLHttpRequest();

    request.open('GET', url, true);
    request.responseType = 'arraybuffer';

    /**
     * Appends two ArrayBuffers into a new one.
     * 
     * @param {ArrayBuffer} data The ArrayBuffer that was loaded.
     */
    function play(data) {
      //decode the loaded data
      context.decodeAudioData(data, function(buf) {
        var audioSource = context.createBufferSource();
        audioSource.connect(context.destination);

        // Concatenate the two buffers into one.
        audioSource.buffer = appendBuffer(buf, buf);
        audioSource.noteOn(0);
        audioSource.playbackRate.value = 1;
      });

    };

    // When the song is loaded asynchronously try to play it.
    request.onload = function() {
      play(request.response);
    }

    request.send();
  }


  loadSongWebAudioAPI('loop.mp3');
}

window.addEventListener('load',init,false);

有轻微的播放间隙 - 这是因为您在声音样本的开头有近 50 毫秒的静音,而不是由于循环问题。

希望这可以帮助!

于 2013-01-03T22:14:29.597 回答
4

如果您需要从数组(不仅是 2 个)追加/连接缓冲区列表,这里有一个解决方案。我刚刚调整了@Cwilso 代码(感谢您的帮助;)

function concatBuffer(_buffers) {
    // _buffers[] is an array containig our audiobuffer list

    var buflengh = _buffers.length;
    var channels = [];
    var totalDuration = 0;

    for(var a=0; a<buflengh; a++){
        channels.push(_buffers[a].numberOfChannels);// Store all number of channels to choose the lowest one after
        totalDuration += _buffers[a].duration;// Get the total duration of the new buffer when every buffer will be added/concatenated
    }

    var numberOfChannels = channels.reduce(function(a, b) { return Math.min(a, b); });;// The lowest value contained in the array channels
    var tmp = context.createBuffer(numberOfChannels, context.sampleRate * totalDuration, context.sampleRate);// Create new buffer

    for (var b=0; b<numberOfChannels; b++) {
        var channel = tmp.getChannelData(b);
        var dataIndex = 0;

        for(var c = 0; c < buflengh; c++) {
            channel.set(_buffers[c].getChannelData(b), dataIndex);
            dataIndex+=_buffers[c].length;// Next position where we should store the next buffer values
        }
    }
    return tmp;
}
于 2018-07-12T14:14:00.940 回答