Web Audio API Demo

This demo uses the Web Audio API to adjust the volume of two videos, based on the position of the mouse. By moving the mouse to the top of the page, the upper video gets louder, while the volume of the lower one drops. By moving the mouse to the bottom of the page, the opposite happens. In addition to this, by moving the mouse left or right, the stereo audio stream can be panned.

This demo can be implemented as follows:

var CurX;
var CurY;
var width = screen.width;
var height = screen.height;

var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioCtx = new AudioContext();

// Create source nodes
var sourceNode = player.audio.createAudioSourceNode(audioCtx);
var sourceNode2 = player2.audio.createAudioSourceNode(audioCtx);

// Create gain and panner nodes for first player
var gainNode = audioCtx.createGain();
var pannerNode = audioCtx.createStereoPanner();

// Create gain and panner nodes for second player
var gainNode2 = audioCtx.createGain();
var pannerNode2 = audioCtx.createStereoPanner();

// Set up graph structure
sourceNode.connect(pannerNode);
pannerNode.connect(gainNode);
gainNode.connect(audioCtx.destination);
    
sourceNode2.connect(pannerNode2);
pannerNode2.connect(gainNode2);
gainNode2.connect(audioCtx.destination);

player.addEventListener('loadedmetadata', startUpdating);
function startUpdating() {
    document.onmousemove = updatePage;
}

function updatePage(e) {
    CurY = e.screenY;
    CurX = e.screenX;
    // gain = 1 at CurY = 0, gain = 0 at CurY = height
    gainNode.gain.value = (height - CurY)/ height;
    // gain2 = 0 at CurY = 0, gain2 = 1 at CurY = height
    gainNode2.gain.value = CurY / height;
    // panner = -1 at CurX = 0, panner = 1 at CurX = width
    var panValue = (2 * CurX / width) - 1;
    pannerNode.pan.value = panValue;
    pannerNode2.pan.value = panValue;
}

 

Request a demo