Search code examples
audiohtml5-audioweb-audio-apiaudiocontextaudio-panning

Web audio api stereo panner for multiple audio


I have added the feature to control panning of sounds but I cannot get all sound into a single buffer channel. Now I found a project on github https://mdn.github.io/webaudio-examples/stereo-panner-node/ . The main problem int this github project is though it works on almost all devices it only play a single sound. I tried to modify it using queryselectorall for it to work on all noises throughout my website but no luck.

var audioCtx;
var myAudio = document.querySelectorAll("audio");
var panControl = document.querySelector('.panning-control');
var panValue = document.querySelector('.panning-value');

audioCtx = new window.AudioContext();
var panNode = audioCtx.createStereoPanner();
  
  for (var i = 0; i < myAudio.length; i++) 
{
  source = audioCtx.createMediaElementSource(myAudio[i]);
  source.connect(panNode);
}
  panNode.connect(audioCtx.destination);
 
panControl.oninput = function() {
    panNode.pan.value = panControl.value;
    
  }

The above code is my modified code. It pans all audio but it works only for a limited number of devices and especially not on phone. No sound comes from audio when I add the modified code on some devices. Help me add multiple sounds into a single buffer channel so I can add panning function to control all sounds through a single slider/seeker.

Your help would be appreciated.


Solution

  • Thanks for no help guys but just beating around the bush. Btw i found the answer to the question. Hope it helps some other person.

    let audioCtx;
    const myAudio = document.getElementsByClassName('allmusic');
    const myScript = document.querySelector('script');
    const panControl = document.querySelector('.panning-control');
    const panValue = document.querySelector('.panning-value');
    
    
    for(let i = 0; i<myAudio.length; i++){
       myAudio[i].addEventListener('play', () => {
    
      if(!audioCtx) {
        audioCtx = new window.AudioContext();
      }
      let source = audioCtx.createMediaElementSource(myAudio[i]);
      let panNode = audioCtx.createStereoPanner();
      panControl.oninput = function() {
        panNode.pan.value = panControl.value;
        panValue.innerHTML = panControl.value;
      }
      source.connect(panNode);
      panNode.connect(audioCtx.destination);
     });
    }
    

    For the panning control

    <input class="panning-control" type="range" min="-1" max="1" step="0.1" value="0">
    

    The audio selector will select all audios with class "allmusic". You can also use it as

    const myAudio = document.querySelectorAll('audio');
    

    I just added a different way to select all elements for click events Enjoy.