2012-07-10 67 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