Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pause Web Audio API sound playback

How can i create a pause function for my audio? I already have a play function in my script below.

http://pastebin.com/uRUQsgbh

function loadSound(url) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'arraybuffer';

    // When loaded decode the data
    request.onload = function() {

        // decode the data
        context.decodeAudioData(request.response, function(buffer) {
            // when the audio is decoded play the sound
            playSound(buffer);
        }, onError);
    }
    request.send();
}

function playSound(buffer) {
    sourceNode.buffer = buffer;
    sourceNode.noteOn(0);
}

But how can i pause or stop it?

like image 308
Mike Boutin Avatar asked Dec 04 '22 12:12

Mike Boutin


1 Answers

The short answer is "you can't pause it - you can stop it, as idbehold says, by calling sourceNode.noteOff(0);".

You can't pause it for the same reason there isn't a "pause" button on an audio cable - because data keeps running through it. You could implement a recorder node that can pause, but at some point it's going to be buffering up a huge amount of data if you don't unpause it.

The usual way to implement this scenario is to keep track of where you are in the playback (e.g. by remembering when you started), and then when you want to pause you remember that offset, call noteOff(0), then when you want to re-start the playback create a new node pointing to the same buffer and call noteOnGrain with the offset.

like image 163
cwilso Avatar answered Dec 28 '22 09:12

cwilso