2012-07-10 71 views
0

我想編寫一個HTML5 Web Audio API的基本腳本,可以播放一些音頻文件。但我不知道如何卸載播放的音頻並加載另一個音頻。在我的腳本中,兩個音頻文件在同一時間播放,但不是我想要的。Web Audio API:如何加載另一個音頻文件?

這裏是我的代碼:

var context, 
    soundSource, 
    soundBuffer; 

// Step 1 - Initialise the Audio Context 
context = new webkitAudioContext(); 

// Step 2: Load our Sound using XHR 
function playSound(url) { 
    // Note: this loads asynchronously 
    var request = new XMLHttpRequest(); 
    request.open("GET", url, true); 
    request.responseType = "arraybuffer"; 

    // Our asynchronous callback 
    request.onload = function() { 
     var audioData = request.response; 
     audioGraph(audioData); 
    }; 

    request.send(); 
} 

// This is the code we are interested in 
function audioGraph(audioData) { 
    // create a sound source 
    soundSource = context.createBufferSource(); 

    // The Audio Context handles creating source buffers from raw binary 
    soundBuffer = context.createBuffer(audioData, true/* make mono */); 

    // Add the buffered data to our object 
    soundSource.buffer = soundBuffer; 

    // Plug the cable from one thing to the other 
    soundSource.connect(context.destination); 

    // Finally 
    soundSource.noteOn(context.currentTime); 
} 

// Stop all of sounds 
function stopSounds(){ 
    // How can do this? 
} 


// Events for audio buttons 
document.querySelector('.pre').addEventListener('click', 
    function() { 
     stopSounds(); 
     playSound('http://thelab.thingsinjars.com/web-audio-tutorial/hello.mp3'); 
    } 
); 
document.querySelector('.next').addEventListener('click', 
    function() { 
     stopSounds(); 
     playSound('http://thelab.thingsinjars.com/web-audio-tutorial/nokia.mp3'); 
    } 
); 

回答

2

你應該預加載聲音到緩衝區中一次,在發射,並簡單地重置AudioBufferSourceNode只要你想播放。

要播放順序多的聲音,您需要使用noteOn(time),一前一後,基於緩衝區各自的長度來安排他們。

要停止的聲音,使用noteOff

聽起來像是你缺少一些基本的網絡音頻的概念。這個(以及更多)詳細描述,並在HTML5Rocks tutorialFAQ中用樣本顯示。

+0

謝謝,但我是一個初學者,我不知道如何重置AudioBuferSouceNode。我會先閱讀教程。 – Sean 2012-07-11 02:55:17