简体   繁体   中英

Web audio API: how to play and stop audio?

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:

  1. what's the difference between those two playing audio methods?

  2. How can i stop the sound manually?

Any help is greatly appreciated.

You can pause the audio element and set its time to 0 , so that you effectively have "stop" functionality: http://jsfiddle.net/Z5ZuJ/ .

audio0.pause();
audio0.currentTime = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM