1

I want to control the audio balance when I use this code

var oscillator = audioCtx.createOscillator();

oscillator.type = 'square';
oscillator.frequency.value = frequency; // value in hertz
oscillator.connect(audioCtx.destination);
oscillator.start();
setTimeout(function(){oscillator.stop();}, duration);   

and also when I play a local mp3 file. How can I do this?

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
OMGsh
  • 168
  • 11
  • I've seen this https://stackoverflow.com/questions/28111136/web-audio-api-pan-audio-left-right-controlling-gain and https://stackoverflow.com/questions/14378305/how-to-create-very-basic-left-right-equal-power-panning-with-createpanner/20850704#20850704 but no code from there works in my (uptodate) FF. – OMGsh Aug 30 '17 at 20:26
  • in http://jsbin.com/ObEfamI/1/edit?js,console,output for example I get the error "@ObEfamI.js:68:1" – OMGsh Aug 31 '17 at 07:18
  • Did you try to implement the `createPanner` from the second answer you linked to? (there is also a [`createStereoPanner`](https://devdocs.io/dom/audiocontext/createstereopanner)). –  Sep 05 '17 at 14:21
  • Also worth looking at https://developer.mozilla.org/en-US/docs/Web/API/PannerNode – Caltor Sep 05 '17 at 14:21

1 Answers1

1

Add a StereoPannerNode to the chain using createStereoPanner:

var oscillator = audioCtx.createOscillator();
var panner = audioCtx.createStereoPanner();

oscillator.type = 'square';
oscillator.frequency.value = frequency;  // value in hertz
oscillator.connect(panner);              // connect audio source to panner
panner.connect(audioCtx.destination);    // connect panner to output
oscillator.start();

Now you can control the L/R using:

panner.pan.value = someValue;   // value in the range -1 (L) to 1 (R)

Functional example:

var audioCtx = new (AudioContext || webkitAudioContext)();
var oscillator = audioCtx.createOscillator();
var panner = audioCtx.createStereoPanner();

oscillator.type = 'square';
oscillator.frequency.value = 440; // value in hertz
oscillator.connect(panner);
panner.connect(audioCtx.destination);
oscillator.start();

document.querySelector("input").oninput = function() {
  panner.pan.value = +this.value; 
};

setInterval(function() {
  oscillator.frequency.value = Math.round(Math.random() * 10) * 400 + 200;
}, 100);
<label>L <input type=range min=-1 max=1 value=0 step=0.01> R</label>