我一直在使用 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);