Play different sound frequencies when scrolling a web page

Date: January 14, 2023 Web Audio APIPlay FrequenciesJavascriptScrolling Web PageSounds
Play different sound frequencies when scrolling a web page

How to play different sound frequencies when scrolling a web page using Web Audio API.

Below you will find sample code on how to use the Web Audio API to to play different frequency sounds while you scroll the page.

 

JavaScript


var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var oscillator = audioCtx.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.value = 440;
oscillator.start();

window.addEventListener('scroll', function() {
    var scrollPos = window.pageYOffset;
    var frequency = scrollPos * 2;
    oscillator.frequency.value = frequency;
});