The createStereoPanner()
method of the BaseAudioContext
interface creates a StereoPannerNode
, which can be used to apply stereo panning to an audio source. It positions an incoming audio stream in a stereo image using a low-cost panning algorithm.
In our StereoPannerNode example (see source code) HTML we have a simple <audio>
element along with a slider <input>
to increase and decrease pan value. In the JavaScript we create a MediaElementAudioSourceNode
and a StereoPannerNode
, and connect the two together using the connect()
method. We then use an oninput
event handler to change the value of the StereoPannerNode.pan
parameter and update the pan value display when the slider is moved.
Moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively.
const audioCtx = new AudioContext();
const myAudio = document.querySelector("audio");
const panControl = document.querySelector(".panning-control");
const panValue = document.querySelector(".panning-value");
const source = audioCtx.createMediaElementSource(myAudio);
const panNode = audioCtx.createStereoPanner();
panControl.oninput = () => {
panNode.pan.setValueAtTime(panControl.value, audioCtx.currentTime);
panValue.innerHTML = panControl.value;
};
source.connect(panNode);
panNode.connect(audioCtx.destination);