triad chord (v2)
delayed version
by jmchen
HTML
<button id='noteon' style='margin:10px'>Note On</button>
<button id='noteoff' style='margin:10px'>Note Off</button>
<br/>
<button id='oneBeat' style='margin:10px'>Broken Chord</button>
<p id='hint'></p>
JavaScript
var noteTable = [{
note: 'c4',
frequency: 261.63
}, {
note: 'e4',
frequency: 329.63
}];
/////////////////////////////////////////////////////////////////////
var ac = new(window.AudioContext || window.webkitAudioContext);
function Sound(frequency, type) {
this.frequency = frequency || 440;
this.type = type || 'triangle';
};
Sound.prototype.noteOn = function () {
this.osc = ac.createOscillator();
this.osc.connect(ac.destination);
this.osc.frequency.value = this.frequency;
this.osc.type = this.type;
this.osc.start(0);
};
Sound.prototype.noteOff = function () {
this.osc.stop(0);
};
var sounds = [];
for (var i = 0; i < noteTable.length; i++) {
var ss = new Sound(noteTable[i].frequency);
sounds.push(ss);
}
$('#noteon').click(function () {
sounds[0].noteOn();
sounds[1].noteOn();
$('#hint').text('chord ON!');
});
$('#noteoff').click(function () {
sounds[0].noteOff();
sounds[1].noteOff();
$('#hint').text('chord off!');
});
$('#oneBeat').click(function () {
/* setTimeout (function() {
sounds[0].noteOn();
}, 0);
*/
setTimeout (sounds[0].noteOn(),0);
setTimeout (sounds[0].noteOff(),500);
/* setTimeout (function() {
sounds[0].noteOff();
}, 500);*/
setTimeout (function() {
sounds[1].noteOn();
}, 500);
setTimeout (function() {
sounds[1].noteOff();
}, 1000);
setTimeout (function() {
sounds[0].noteOn();
sounds[1].noteOn();
}, 1000);
setTimeout (function() {
sounds[0].noteOff();
sounds[1].noteOff();
}, 2000);
$('#hint').text('c4 e4 chord!');
});
//////////////////////////////////////////////
// problem: cannot play twice
// http://stackoverflow.com/questions/9439585/play-an-audiobuffersourcenode-twice
// http://stackoverflow.com/questions/15261030/web-audio-start-and-stop-oscillator-then-start-it-again