Mouse-controlled playback

Today, we learned how to control volume and panning in a Web Audio API graph via the position of the mouse on the screen. The example below applies these ideas to our web radio live stream.
news
Author

Florian Hollerweger

Published

December 10, 2025

Example

Give it a try – just hit play below and move the mouse. Move the mouse up to make sound louder, or down to make it softer. Moving the mouse on the left-right axis will pan the sound accordingly between your left and right loudspeaker.

Note that the mouse will only control playback in the current browser window.

Code

In the HTML code, note the crossorigin='anonymous', which is required to get this to work with our stream (in contrast to a local sound file).

<audio controls id='stream' onplay='context.resume()' crossorigin='anonymous'>
  <source src="http://85.215.66.113:8000/radio.ogg" type="audio/ogg">
  <source src="http://85.215.66.113:8000/radio" type="audio/mpeg">
</audio>

<script>
    // Source: https://docs.theoplayer.com/knowledge-base/03-playback/05-basic-guide-web-audio-api.md

    // Nodes
    let context = new AudioContext()
    let source = context.createMediaElementSource(stream)
    let panpot = context.createStereoPanner()
    let master = new GainNode(context,{gain:0.1})

    // Connections
    source.connect(panpot).connect(master).connect(context.destination)

    // Callback to monitor mouse movement
    var updatePage = function (e) { // 'e' is shorthand for 'event' object: https://stackoverflow.com/a/10323409
        panpot.pan.value = (2 * e.screenX) / screen.width - 1
        master.gain.value = (screen.height - e.screenY) / screen.height
    }

    document.onmousemove = updatePage
</script>