-
Notifications
You must be signed in to change notification settings - Fork 6
/
tinymusic.js
198 lines (168 loc) · 5.97 KB
/
tinymusic.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
//TinyMusic.js by Kevin Cennis
(function ( root, factory ) {
if ( typeof define === 'function' && define.amd ) {
define( [ 'exports' ], factory );
} else if ( typeof exports === 'object' && typeof exports.nodeName !== 'string' ) {
factory( exports );
} else {
factory( root.TinyMusic = {} );
}
}( this, function ( exports ) {
var enharmonics = 'B#-C|C#-Db|D|D#-Eb|E-Fb|E#-F|F#-Gb|G|G#-Ab|A|A#-Bb|B-Cb',
middleC = 440 * Math.pow( Math.pow( 2, 1 / 12 ), -9 ),
numeric = /^[0-9.]+$/,
octaveOffset = 4,
space = /\s+/,
num = /(\d+)/,
offsets = {};
// populate the offset lookup (note distance from C, in semitones)
enharmonics.split('|').forEach(function( val, i ) {
val.split('-').forEach(function( note ) {
offsets[ note ] = i;
});
});
// create a new Note instance from a string
function Note( str ) {
var couple = str.split( space );
// frequency, in Hz
this.frequency = Note.getFrequency( couple[ 0 ] ) || 0;
// duration, as a ratio of 1 beat (quarter note = 1, half note = 0.5, etc.)
this.duration = Note.getDuration( couple[ 1 ] ) || 0;
}
// convert a note name (e.g. 'A4') to a frequency (e.g. 440.00)
Note.getFrequency = function( name ) {
var couple = name.split( num ),
distance = offsets[ couple[ 0 ] ],
octaveDiff = ( couple[ 1 ] || octaveOffset ) - octaveOffset,
freq = middleC * Math.pow( Math.pow( 2, 1 / 12 ), distance );
return freq * Math.pow( 2, octaveDiff );
};
Note.getDuration = function( symbol ) {
return numeric.test( symbol ) ? parseFloat( symbol ) :
symbol.toLowerCase().split('').reduce(function( prev, curr ) {
return prev + ( curr === 'w' ? 4 : curr === 'h' ? 2 :
curr === 'q' ? 1 : curr === 'e' ? 0.5 :
curr === 's' ? 0.25 : 0 );
}, 0 );
};
// create a new Sequence
function Sequence( ac, tempo, arr ) {
this.ac = ac || new AudioContext();
this.createFxNodes();
this.tempo = tempo || 120;
this.loop = true;
this.smoothing = 0;
this.staccato = 0;
this.notes = [];
this.push.apply( this, arr || [] );
}
// create gain and EQ nodes, then connect 'em
Sequence.prototype.createFxNodes = function() {
var eq = [ [ 'bass', 100 ], [ 'mid', 1000 ], [ 'treble', 2500 ] ],
prev = this.gain = this.ac.createGain();
eq.forEach(function( config, filter ) {
filter = this[ config[ 0 ] ] = this.ac.createBiquadFilter();
filter.type = 'peaking';
filter.frequency.value = config[ 1 ];
prev.connect( prev = filter );
}.bind( this ));
prev.connect( this.ac.destination );
return this;
};
// accepts Note instances or strings (e.g. 'A4 e')
Sequence.prototype.push = function() {
Array.prototype.forEach.call( arguments, function( note ) {
this.notes.push( note instanceof Note ? note : new Note( note ) );
}.bind( this ));
return this;
};
// create a custom waveform as opposed to "sawtooth", "triangle", etc
Sequence.prototype.createCustomWave = function( real, imag ) {
// Allow user to specify only one array and dupe it for imag.
if ( !imag ) {
imag = real;
}
// Wave type must be custom to apply period wave.
this.waveType = 'custom';
// Reset customWave
this.customWave = [ new Float32Array( real ), new Float32Array( imag ) ];
};
// recreate the oscillator node (happens on every play)
Sequence.prototype.createOscillator = function() {
this.stop();
this.osc = this.ac.createOscillator();
// customWave should be an array of Float32Arrays. The more elements in
// each Float32Array, the dirtier (saw-like) the wave is
if ( this.customWave ) {
this.osc.setPeriodicWave(
this.ac.createPeriodicWave.apply( this.ac, this.customWave )
);
} else {
this.osc.type = this.waveType || 'square';
}
this.osc.connect( this.gain );
return this;
};
// schedules this.notes[ index ] to play at the given time
// returns an AudioContext timestamp of when the note will *end*
Sequence.prototype.scheduleNote = function( index, when ) {
var duration = 60 / this.tempo * this.notes[ index ].duration,
cutoff = duration * ( 1 - ( this.staccato || 0 ) );
this.setFrequency( this.notes[ index ].frequency, when );
if ( this.smoothing && this.notes[ index ].frequency ) {
this.slide( index, when, cutoff );
}
this.setFrequency( 0, when + cutoff );
return when + duration;
};
// get the next note
Sequence.prototype.getNextNote = function( index ) {
return this.notes[ index < this.notes.length - 1 ? index + 1 : 0 ];
};
// how long do we wait before beginning the slide? (in seconds)
Sequence.prototype.getSlideStartDelay = function( duration ) {
return duration - Math.min( duration, 60 / this.tempo * this.smoothing );
};
// slide the note at <index> into the next note at the given time,
// and apply staccato effect if needed
Sequence.prototype.slide = function( index, when, cutoff ) {
var next = this.getNextNote( index ),
start = this.getSlideStartDelay( cutoff );
this.setFrequency( this.notes[ index ].frequency, when + start );
this.rampFrequency( next.frequency, when + cutoff );
return this;
};
// set frequency at time
Sequence.prototype.setFrequency = function( freq, when ) {
this.osc.frequency.setValueAtTime( freq, when );
return this;
};
// ramp to frequency at time
Sequence.prototype.rampFrequency = function( freq, when ) {
this.osc.frequency.linearRampToValueAtTime( freq, when );
return this;
};
// run through all notes in the sequence and schedule them
Sequence.prototype.play = function( when ) {
when = typeof when === 'number' ? when : this.ac.currentTime;
this.createOscillator();
this.osc.start( when );
this.notes.forEach(function( note, i ) {
when = this.scheduleNote( i, when );
}.bind( this ));
this.osc.stop( when );
this.osc.onended = this.loop ? this.play.bind( this, when ) : null;
return this;
};
// stop playback, null out the oscillator, cancel parameter automation
Sequence.prototype.stop = function() {
if ( this.osc ) {
this.osc.onended = null;
this.osc.disconnect();
this.osc = null;
}
return this;
};
exports.Note = Note;
exports.Sequence = Sequence;
}));