AudioContext panning audio of playing media

前端 未结 2 665
Happy的楠姐
Happy的楠姐 2020-12-31 20:55

I wonder if is there a way to pan the audio of a video with JavaScript.

The same way you can adjust volume, I need to pan an stereo audio left to right or right to l

2条回答
  •  悲&欢浪女
    2020-12-31 21:38

    I added ambient audio on one of my pages that I'm trying to build for a game. Here's my experimentation with panning that I'll be using later on certain sound effects throughout the game. Took forever to realize there was this nice createStereoPanner thing, which simplified the whole process significantly. I tested it with a video and it worked just as well.

    var ambientAudio = new Audio('./ambientVideo.mp4');
    
    document.addEventListener('keydown', ambientAudioControl)
    function ambientAudioControl(e) {
      if (e.keyCode === 37) panToLeft()
      if (e.keyCode === 39) panToRight()
      if (e.keyCode === 40) panToStereo()
    }
    
    const ambientContext = new AudioContext();
    const source = ambientContext.createMediaElementSource(ambientAudio);
    const ambientPan = ambientContext.createStereoPanner()
    
    function panToLeft(){ ambientPan.pan.value = -1 }
    function panToRight(){ ambientPan.pan.value = 1 }
    function panToStereo(){ ambientPan.pan.value = 0 }
    
    source.connect(ambientPan)
    ambientPan.connect(ambientContext.destination)
    ambientAudio.play()

提交回复
热议问题