How to change sound volume using webAudio api gain property

A quick function to adjust html5 web audio gain value or "audio volume"
sound gain value is controlled by creating a gain node and setting it's gain value 0-1

where 0 is the lowest value 1 is the maximum gain value 

let sound = function sound(url, params) {
    // params
    let loop = params.loop;
    // make a context
    let audioContext = new (window.AudioContext || window.webkitAudioContext)();
    let source = audioContext.createBufferSource();

    let gainNode = audioContext.createGain()
        gainNode.gain.value = 0.05 // sound percentage

    let request = new XMLHttpRequest();
request.open('GET', url, true);

    request.responseType = 'arraybuffer';
    request.onload = function() {
            audioContext.decodeAudioData(request.response, function(buffer) {
            source.buffer = buffer;
            
            gainNode.connect(audioContext.destination)
            source.connect(gainNode)
            source.loop = loop;
            source.start(0);

        }, (e) => {
            throw new Error('Audio error! ', e);
        });
    }

    request.send();
}

Comments

Popular posts from this blog

How to use canvas context rect method for drawing rectangles

JavaScript introduction to variables

How to draw clouds on HTML5 Canvas

Solutions to blocked URLs on Facebook

How to create zip archives in nodejs