Reputation: 3265
In order to not chock the listener I want to play a wave but the volume should not be played at 100% ratio from early, it should go from 0% to 100% in duration of 2secondes for instance.
I tought of a setTimeout and I increase the gain by the time, but I don't know if is there any other better approch
var source = aCtx.createBufferSource();
source.buffer = buf;
var gainNode = aCtx.createGain();
gainNode.gain.value = 0
source.connect(gainNode);
gainNode.connect(aCtx.destination);
source.start(0);
setTimeout(function() {
gainNode.gain.value = 0.5
}, 1000)
setTimeout(function() {
gainNode.gain.value = 1
}, 2000)
Upvotes: 2
Views: 1826
Reputation: 6540
The Web Audio API provides a library function for this.
AudioParam.linearRampToValueAtTime(value, endTime)
value
A floating point number representing the value the AudioParam will ramp to by the given time.
endTime
A double representing the exact time (in seconds) after the ramping starts that the changing of the value will stop.
So in your case use
gainNode.gain.linearRampToValueAtTime(0, 0)
gainNode.gain.linearRampToValueAtTime(1, 2)
Upvotes: 6
Reputation: 313
Make it dynamic by simply using some kind of lerp function, there are many out there. The basic idea is that you get a value being interpolated between two of your starting values. Example:
value 1 = 5
value 2 = 1
interpolation amount = 0.4 (40%)
then the result should be exactly 2.6
said function might just look like this
Math.lerp = function (value1, value2, amount) {
amount = amount < 0 ? 0 : amount;
amount = amount > 1 ? 1 : amount;
return value1 + (value2 - value1) * amount;
};
In your specific scenario you would take the min and max volume as the both values and then regulate the amount using the time that has passed. Probably with some async function call back to this function. hope i could help.
Upvotes: 0