Web Audio API如何命名声音

时间:2014-10-31 16:51:02

标签: javascript audio html5-audio web-audio

所以此刻两个声音被加载到缓冲区中,然后连接到两个源。如何将BufferLoader中的两个声音命名为“kick”和“hihat”,然后使用kick.start(0)播放它们。我知道它一定很容易但我找不到任何东西。

window.onload = init;
var context = new AudioContext();
var bufferLoader;

function init() {

  bufferLoader = new BufferLoader(
    context,
    [
      'kick.wav',
      'hihat.wav',
    ],
    finishedLoading
    );

  bufferLoader.load();
}

function finishedLoading(bufferList) {

  var source1 = context.createBufferSource();
  var source2 = context.createBufferSource();
  source1.buffer = bufferList[0];
  source2.buffer = bufferList[1];

  source1.connect(context.destination);
  source2.connect(context.destination);
  source1.start(0);
  source2.start(0);
}    

1 个答案:

答案 0 :(得分:1)

如果你愿意,你可以使用我为自己写的抽象:

function audioFileLoader(fileDirectory) {
    var soundObj = {};
    soundObj.fileDirectory = fileDirectory;

    var getSound = new XMLHttpRequest();
    getSound.open("GET", soundObj.fileDirectory, true);
    getSound.responseType = "arraybuffer";
    getSound.onload = function() {
        audioContext.decodeAudioData(getSound.response, function(buffer) {
            soundObj.soundToPlay = buffer;

        });
    }

    getSound.send();


    soundObj.play = function() {
        var playSound = audioContext.createBufferSource();
        playSound.buffer = soundObj.soundToPlay;
        playSound.connect(audioContext.destination)
        playSound.start(audioContext.currentTime)
    }

    return soundObj;

};

var snare = audioFileLoader("snare.mp3");


snare.play()