i use web audio API in my game in Chrome. To play the sound, I use web audio API.
I learn it from the article: http://www.html5rocks.com/en/tutorials/webaudio/intro/
window.onload = init;
var context;
var bufferLoader;
function init() {
context = new webkitAudioContext();
bufferLoader = new BufferLoader(
context,
[
'0.mp3',
'2.mp3',
],
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.noteOn(0);
source2.noteOn(0);
}
However, the sounds weren't played. Let alone i want to use noteOff(0) to stop them later.
Then i found this article http://updates.html5rocks.com/2012/02/HTML5-audio-and-the-Web-Audio-API-are-BFFs
And i change my code to:
var context = new webkitAudioContext();
var analyser = context.createAnalyser();
var source;
var audio0 = new Audio();
audio0.src = '0.mp3';
audio0.controls = true;
audio0.autoplay = true;
audio0.loop = true;
source = context.createMediaElementSource(audio0);
source.connect(analyser);
analyser.connect(context.destination);
This time it is played!
And here comes my problem: I want to stop the sound with a button.
I tried to change the audio0.autoplay =false;
var play0 = false;
$("#0").click(function(){
if(play0===false){
audio0.src = '0.mp3';
audio0.controls = true;
audio0.autoplay = true;
audio0.loop = true;
source = context.createMediaElementSource(audio0);
source.connect(analyser);
analyser.connect(context.destination);
play0=true;}
if(paly0){
audio0.autoplay=false;}
});
In stead of getting stop, it is played again every time i click the button.
Two questions:
what's the difference between those two playing audio methods?
How can i stop the sound manually?
Any help is greatly appreciated.
audio0.pause()
? – pimvdb.pause()
and then.currentTime = 0;
. – pimvdbcreateMediaElementSource
currently only fully works in Chrome. The AnalyzerNode will only get populated with correct data on Chrome, on Safari the data will always empty (or rather, all 0s). – idbehold