Search code examples
javascriptweb-audio-api

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 the source node). However, if I call stop(0) on an audio source node, is that event triggered? The specs don't seem clear on that.

I can try this out on various browsers, but I want to know the proper standard behavior for this. Does the ended event fire when a source node is proactively stopped? Or does the ended event only fire if audio finishes playing?


Solution

  • 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>