Skip to content Skip to sidebar Skip to footer

Does Calling Stop() On A Source Node Trigger An Ended Event?

According to the web audio API specs http://webaudio.github.io/web-audio-api/ I can assign an event handler that runs when a source node is done playing (the onended attribute of t

Solution 1:

Yes it does. onended event gets fired when audio is finished playing or when stop() has been called.

Example from MDN AudioContext docs

var audioCtx = new(window.AudioContext || window.webkitAudioContext)();
var button = document.querySelector('button');
var stop = document.querySelector('#stop');
var source;

// Stereo
var channels = 2;
// Create an empty two second stereo buffer at the
// sample rate of the AudioContext
var frameCount = audioCtx.sampleRate * 2.0;

var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);

button.onclick = function () {
    // Fill the buffer with white noise;
    //just random values between -1.0 and 1.0
    for (var channel = 0; channel < channels; channel++) {
        // This gives us the actual ArrayBuffer that contains the data
        var nowBuffering = myArrayBuffer.getChannelData(channel);
        for (var i = 0; i < frameCount; i++) {
            // Math.random() is in [0; 1.0]
            // audio needs to be in [-1.0; 1.0]
            nowBuffering[i] = Math.random() * 2 - 1;
        }
    }

    // Get an AudioBufferSourceNode.
    // This is the AudioNode to use when we want to play an AudioBuffer
    source = audioCtx.createBufferSource();
    // set the buffer in the AudioBufferSourceNode
    source.buffer = myArrayBuffer;
    // connect the AudioBufferSourceNode to the
    // destination so we can hear the sound
    source.connect(audioCtx.destination);
    // start the source playing
    source.start();

    source.onended = function () {
        alert('ended');
    };
};

stop.onclick = function() {
    source.stop();
};
<h1>AudioBuffer example</h1>

<button>Make white noise</button>
<button id="stop">stop()</button>

Solution 2:

onended of type EventHandler,

A property used to set the EventHandler (described in HTML[HTML]) for the ended event that is dispatched to AudioBufferSourceNode node types. When the playback of the buffer for an AudioBufferSourceNode is finished, an event of type Event (described in HTML [HTML]) will be dispatched to the event handler.

It states that it fires at the end of the audio data, or when it is being stopped.

These lines got me confused:

    void start (optional double when = 0, optional double offset = 0, optional double duration);
    void stop (optional double when = 0);
            attribute EventHandler onended;

Post a Comment for "Does Calling Stop() On A Source Node Trigger An Ended Event?"