Generating sound on the fly with javascript/html5

前端 未结 7 1895
庸人自扰
庸人自扰 2020-12-12 13:09

Is it possible to generate a constant sound stream with javascript/html5? For example, to generate a perpetual sine wave, I would have a callback function, that would be cal

7条回答
  •  醉酒成梦
    2020-12-12 13:47

    This is what I have looked for like forever and in the end I managed to do it myself like I wanted. Maybe you will like it too. Simple slider with frequency and push on/off:

    buttonClickResult = function () {
    	var button = document.getElementById('btn1');
    
    	button.onclick = function buttonClicked()  {
    
    		if(button.className=="off")  {
    			button.className="on";
    			oscOn ();
    		}
    
    		else if(button.className=="on")  {
    			button.className="off";
    			oscillator.disconnect();
    		}
    	}
    };
    
    buttonClickResult();
    
    var oscOn = function(){
    
    	window.AudioContext = window.AudioContext || window.webkitAudioContext;
    	var context = new AudioContext();
    	var gainNode = context.createGain ? context.createGain() : context.createGainNode();
    
    	//context = new window.AudioContext();
    	oscillator = context.createOscillator(),
    			oscillator.type ='sine';
    
    	oscillator.frequency.value = document.getElementById("fIn").value;
    	//gainNode = createGainNode();
    	oscillator.connect(gainNode);
    	gainNode.connect(context.destination);
    	gainNode.gain.value = 1;
    	oscillator.start(0);
    };

    Frekvence [Hz]


提交回复
热议问题