Search code examples
javascriptweb-audio-api

how to scale web audio oscillator from (-1,1) to (x,y)


I would like to map the signal of an oscillator from (-1,1) to (x,y) For what I've understand so far, gain nodes can be used for that.

if i connect my oscillator to a gain node that value is 1, I've get back my signal in the range (0,2)

if I feed this signal into another gain at value 0.25 i've get back a signal in range (0,0.5)

but how to do if I want my signal to be in the range (0.5, 1) ?

I'm wandering why we cannot simply map a function over a signal.

like signal.map(function(x){return x + 0.5})


Solution

  • For the specific scenario you mention ("[what] if I want my signal to be in the range (0.5, 1)?"), you should connect your (0,0.5) signal into the same node as a ConstantSourceNode:

    var constant = new ConstantSourceNode( { offset: 0.5 } );
    constant.connect( /* same node as your signal */ );
    

    For the more general case - like, you want to do non-linear mapping - use a WaveShaperNode.