-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch.js
426 lines (322 loc) · 10.5 KB
/
sketch.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//Welcome to Rethinking Production Tools with
// Rushali, Stanlyn and Dominic
//
//Tuner, audio to MIDI musical web app
//Much thanks to:
//
//Web Audio Demos Pitch Detect Example:
//https://webaudiodemos.appspot.com/pitchdetect/index.html
//Tone.js, with MidiConvert.js
//p5.js
//
//Rune Madsen, Patrick Hebron, Yotam Mann, Justin Peake
var canvas;
var mic = new p5.AudioIn();
var micon = 0;
var mySound;
var mySoundRecorder;
var isRecording = 0;
var recordbutton;
var rID = null;
var song;
var amp1 = new p5.Amplitude();
var fft = new p5.FFT(0.8, 256);
var volhistory = [];
var w;
var vol;
var diam;
var spectrum;
var recInfoStatus;
//html elements for UI
var div2 = document.getElementById("d2");
var div3 = document.getElementById("d3");
var div3 = document.getElementById("detune");
//This is a MidiConvert midi sequence object
var midi;
//midi score part object, for Tone.js note playback
var midiPart;
//synthesizer, for Tone.js voice
var synth = new Tone.PolySynth(6, Tone.Synth).toMaster();
function setup() {
recInfoStatus = [
{ startTime: 0 },
{ endTime: 0 },
{ timeLength: 0 },
{ isRecording: false }
//time is obtained by a var with "new Date()"
//timers can be made by setting a start time with Date()
//then an end time later on
//at that point, you calculate the difference, end time minus start time
];
canvas = createCanvas(1000, 500);
canvas.id("maincanvas");
colorMode(HSB);
angleMode(DEGREES);
w = width / 2048;
//We're using p5 for some of the audio functionality
//p5.sound has easy access to the browser microphone
//and the ability to save audio buffers as .wav files easily
amp = new p5.Amplitude();
amp.setInput(mic);
//Making sure that the Tone library shares browser audio context
Tone.setContext(getAudioContext());
toneSampler = new Tone.Sampler({
"loop": false
}).toMaster();
//Using MidiConvert.js from Tone.js
// create a new midi file
midi = MidiConvert.create()
// add a track
midi.track()
// select an instrument by its MIDI patch number
.patch(32);
//Notes can be added later in the following manner:
// chain note events: note, time, duration
//.note(60, 0, 1);
// .note(63, 1, 1)
// .note("C6", 2, 1);
//Simple boolean isRecording status for audio recording
//RecInfoStatus was created for more robust timing control
//should eventually replace this, but for now this works
isRecording = 0;
//p5 audio Mic for recording into a p5 buffer
//Which then can be put into a Tone buffer later on
mic.start();
mic.connect();
mySound = new p5.SoundFile();
mySoundRecorder = new p5.SoundRecorder();
mySoundRecorder.setInput(mic);
//Load a Midi sequence and play through the synth
//
midiPart = new Tone.Part(function (time, note) {
//use the events to play the synth
synth.triggerAttackRelease(note.name, note.duration, time, note.velocity)
}, midi.tracks[0].notes);
midiRecordingLoop = new Tone.Loop(function (time) {
//This is triggered every eighth note.
//When writing MIDI notes in a sequence, we are approximately quantizing as 8th notes
//This is an artistic decision; users may want more or less granularity depending on use
//But quantizing in this way helps us avoid more spastic MIDI recordings
//Determining notes per second
//((Notes Per Beat) x (Beats Per Minute)) / 60secs = Notes Per Second
//Note Value Notes Per Beat
// Quarter Note: 1
// 8th Note: 2
// 8th Note Triplet: 3
// 16th Note: 4
// 16th Note Triplet: 6
// 32nd Note: 8
//For now we will hard code the note per beat.
//Given 8th notes, we will create the note length in seconds and pass to function
//Doing it this way allows us to adjust tempo later without issue
var noteLength = ((8*Tone.Transport.bpm.value)/60)/60;
writeMIDICurrentNote(noteLength);
}, "8n").start(0);
Tone.Transport.bpm.value = midi.header.bpm;
Tone.Transport.start();
}
function draw() {
background(255);
//Visualize mic input
translate(width / 2, height / 2);
spectrum = fft.analyze();
for (var i = 0; i < spectrum.length; i++) {
var angle = map(i, 0, spectrum.length, 0, 360);
var amp2 = spectrum[i];
var r = map(amp2, 0, 256, 100, 700);
var x = r * cos(angle);
var y = r * sin(angle);
tint(255, 126);
stroke(i, 255, 150);
line(0, 0, x, y);
}
//not sure why this has to be set here, but it loops otherwise
toneSampler.loop = 0;
//get mic level
micLevel = mic.getLevel();
}
function checkrecording() {
if (isRecording == 0) {
isRecording = 1;
mySoundRecorder.record(mySound);
recInfoStatus.startTime = new Date();
//console.log(mySound);
// if (currentvalue == "record") {
document.getElementById("record").innerText = "stop";
console.log("recordbutton pressed");
}
else if(isRecording == 1) {
document.getElementById("record").innerText = "record";
console.log("Key Released");
isRecording = 0;
mySoundRecorder.stop();
toneSampler.set(mySound);
theBuffer = mySound.buffer;
recInfoStatus.endTime = new Date();
var timeDiff = recInfoStatus.endTime - recInfoStatus.startTime;
recInfoStatus.timeLength = timeDiff;
}
}
function saveaudio() {
save(mySound, "SoundSample.wav");
//console.log("save audio");
}
function savemidi() {
var data = 'data:audio/midi;base64,' + btoa(midi.encode())
var element = document.createElement('a');
element.setAttribute('href', data);
element.setAttribute('download', 'audioToNotes.mid');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
function playaudio() {
toneSampler.triggerAttackRelease(0, 0); //mimicing playmidi() functionality
toneSampler.triggerAttack(1);
}
function playmidi() {
console.log("playmidi()");
midiPart.stop(); //this makes sure you can re-start
midiPart.start();
}
function playsound() {
playaudio();
//console.log("play sound");
}
function mutemic() {
micon = document.getElementById("micmute").value;
if(micon == "On")
{
mic.amp(0);
document.getElementById("micmute").value = "Off";
document.getElementById("micmute").innerText = "unmute";
console.log("mic muted");
}
else if(micon == "Off") {
//mic.disconnect();
mic.amp(1);
document.getElementById("micmute").value = "On";
document.getElementById("micmute").innerText = "MUTE";
console.log("mic unmuted");
}
//console.log("mute button pressed");
}
function sensitivity() {
//highpass and lowpass hasn't been implemented yet
//so we'll take out the HTML element for now
//it is commented out in the index.html
//console.log("sensitivity was changed");
}
function writeMIDICurrentNote(noteLength) {
if (isRecording) {
//console.log("inside writeMIDICurrentNote");
//"blank" note evaluations seem to mess with the midi recording functionality
//filtering out the "-" values that are generated
//noteElem.innerHTML
if (noteElem.innerHTML != "-") {
currentMIDINote = freqToMidi(pitch);
//freqToMidi is a Tone function
//pitch is a variable from pitchdetect.js
var currentTime = new Date();
var currentRecTime = (currentTime - recInfoStatus.startTime) / 1000;
console.log(currentMIDINote + " @ " + currentRecTime);
midi.tracks[0].patch(32).note(currentMIDINote, currentRecTime, noteLength);
//Note length determined by Tone time signature/bpm
//midiPart .add() function
//.removeAll to clear
//or new midiPart entirely
midiPart = new Tone.Part(function (time, note) {
//use the events to play the synth
synth.triggerAttackRelease(note.name, note.duration, time, note.velocity)
}, midi.tracks[0].notes);
}
}
}
//Here are some keyPress functions that replicate the UI funcionality
//and testing some new/other functionality
function keyPressed() {
if (key == "R") {
//console.log("r pressed");
isRecording = 1;
recInfoStatus.startTime = new Date();
mySoundRecorder.record(mySound);
}
if (key == "P") {
toneSampler.triggerAttackRelease(0, 0);
midiPart.stop();
toneSampler.triggerAttack(1);
midiPart.start();
} if (key == " ") {
toneSampler.triggerAttackRelease(0, 0);
midiPart.stop();
}
if (key == "2") {
mic.amp(0);
testDownload = midi.encode();
save(testDownload, "test.mid");
}
if (key == "1") {
keyboard1.toggle( keyboard1.keys[11], true );
//un-mute mic
mic.amp(1);
}
if (key == "T") {
//pitch and noteElem.innerHTML are in pitchdetect and
//are used for the main text that shows notes in the example
//
//we're using them here to give to a tone.js synth
//Pressing the "T" button will play the note currently analyzed
//(if "blank" it should default to the most recent analysis)
var note = noteFromPitch(pitch);
var currentAnalyzedNote = noteStrings[note % 12];
console.log("t pressed, detected " + currentAnalyzedNote);
synth.triggerAttackRelease([currentAnalyzedNote + "5"], "4n");
}
if (key == "S") {
//save the current audio buffer
//using p5 save functionality for the wav
save(mySound, "SoundSample.wav");
//Saving the current midi sequence
//
//User instructions for testing this:
//
//Make sure mic access works
//Click "Use Live Input" to output notes
//Hold "R" and whistle to record audio and MIDI
//Press "S" to download audio and MIDI files
//
//Encoding the current sequence into the proper Midi format
var data = 'data:audio/midi;base64,' + btoa(midi.encode())
var element = document.createElement('a');
element.setAttribute('href', data);
element.setAttribute('download', 'miditest.mid');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
else {
}
}
function keyReleased() {
//console.log("Key Released");
if (isRecording == 1) {
isRecording = 0;
recInfoStatus.endTime = new Date();
var timeDiff = recInfoStatus.endTime - recInfoStatus.startTime;
recInfoStatus.timeLength = timeDiff;
mySoundRecorder.stop();
toneSampler.set(mySound);
theBuffer = mySound.buffer;
}
}
function onoff() {
//console.log("onoff working")
currentvalue = document.getElementById('onoff').value;
if (currentvalue == "Off") {
document.getElementById("onoff").value = "On";
} else {
document.getElementById("onoff").value = "Off";
}
}