-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoscillator.js
123 lines (105 loc) · 2.53 KB
/
oscillator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
$(function () {
/**
* Frequencies.
*/
var frequencies = {
"-": 0,
c: 261.6,
cis: 277.2,
d: 293.7,
dis: 311.1,
e: 329.6,
f: 349.2,
fis: 370.0,
g: 392.0,
gis: 415.3,
a: 440.0,
ais: 466.2,
b: 493.9
//523.3
};
/**
* Note.
*/
var Note = function (note) {
var parts = note.match(/^(\d{1,2})(#?)([a-g\-])(\d)?$/);
var length = parseInt(parts[1], 10);
var accidental = parts[2] !== "";
var note = parts[3] + (accidental ? "is": "");
var octave = parseInt(parts[4], 10);
var frequency = frequencies[note] * Math.pow(2, octave - 1);
var length = Math.floor(1800 / length);
function getFrequency() {
return frequency;
}
function getLength() {
return length;
}
return {
getFrequency: getFrequency,
getLength: getLength
};
};
/**
* Tune.
*/
var Tune = function () {
var notes = [],
index;
function load(code) {
notes = [];
$.each(code.split(" "), function (i, note) {
notes.push(new Note(note));
});
reset();
}
function reset() {
index = 0;
}
function getNote() {
return notes[index++];
}
return {
load: load,
reset: reset,
getNote: getNote
};
};
/**
* Player.
*/
var Player = function () {
var tune,
context = new AudioContext(),
oscillator = null;
function play(t) {
tune = t;
tune.reset();
playNote();
}
function playNote() {
var note = tune.getNote();
oscillator && oscillator.stop();
oscillator = context.createOscillator();
oscillator.type = 0;
oscillator.connect(context.destination);
oscillator.start();
if (!note) {
oscillator.frequency.value = 0;
} else {
oscillator.frequency.value = note.getFrequency() || 0;
setTimeout(playNote, note.getLength());
}
}
return {
play: play
};
};
var player = new Player;
$("#play").click(function () {
var code = $("textarea").val();
var tune = new Tune();
tune.load(code);
player.play(tune);
});
});