Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing volume of oscillator in JavaScript?

I have created a oscillator (as shown below), like MDN said:

// from : https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API

var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var oscillator = audioCtx.createOscillator();
var gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
oscillator.type = 'sine'; // sine wave — other values are 'square', 'sawtooth', 'triangle' and 'custom'
oscillator.frequency.value = 2500; // value in hertz
oscillator.start();

Is there a method to change the volume, like I changed the frequency value?

like image 615
Stardust Avatar asked Jan 28 '26 17:01

Stardust


1 Answers

You can get a variable frequency control with a slider that controls the output frequency:

document.getElementById('slider99').addEventListener('input', slider99change, false);
function slider99change(e) {
    var x = document.getElementById("slider99");
    var s = x.value.toString();
    oz.frequency.value = s;
}

Your oscillator is defined globally elsewhere:

var ozcontext = new (window.AudioContext || window.webkitAudioContext)();
var oz = ozcontext.createOscillator();
var gainNode = ozcontext.createGain();
oz.connect(gainNode);
gainNode.connect(ozcontext.destination);
gainNode.gain.value = 0;
oz.type = 'sine';
oz.frequency.value = 440;
oz.start();
like image 106
pollaris Avatar answered Jan 31 '26 06:01

pollaris