I want to be able to toggle multiple oscillators on and off using click events, and also to only allow single instances at each frequency. The challenge for me is to identify when an oscillator is already playing. I have gone the route of adding a class to the div containing the on/off button, but I don’t think the oscillators I’m creating are linked in any way to the buttons which create them.
Also, I’m using new
without assignment, which has been described as “weird” and probably due to bad coding elsewhere.
My code so far is below. Can someone please tell me how to make it work, or point out a better approach to achieving my goal?
$(document).ready(function(){
var context = new (window.AudioContext || window.webkitAudioContext)();
function oscillator(frequency){
this.oscillator = context.createOscillator();
this.gainNode = context.createGain();
this.gainNode.connect(context.destination);
this.oscillator.frequency.value = frequency;
this.oscillator.connect(this.gainNode);
this.oscillator.start();
this.playing = true;
this.off = function(){
this.oscillator.stop();
this.oscillator.disconnect();
}
}
$('.fork').click(function(){
$el = $(this);
if(!$el.hasClass('playing')){
freq = ($(this).data('frequency'));
new oscillator(freq);
$el.addClass('playing');
return;
}
console.log($el);
});
}); // document.ready end
Sample HTML:
<div class="fork col-xs-4" data-frequency="512">
<img src="images/fork-icon.png" />
</div>
<div class="fork col-xs-4" data-frequency="128">
<img src="images/fork-icon.png" />
</div>