-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
86 lines (71 loc) · 2.55 KB
/
main.js
File metadata and controls
86 lines (71 loc) · 2.55 KB
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
var audioCtx;
var osc;
var timings;
var liveCodeState = [];
const playButton = document.querySelector('button');
//starting with sine wave
var currentWaveform = 'sine';
function initAudio() {
audioCtx = new (window.AudioContext || window.webkitAudioContext)
osc = audioCtx.createOscillator();
timings = audioCtx.createGain();
timings.gain.value = 0;
osc.connect(timings).connect(audioCtx.destination);
osc.start();
scheduleAudio()
}
function scheduleAudio() {
let timeElapsedSecs = 0;
liveCodeState.forEach(noteData => {
timings.gain.setTargetAtTime(1, audioCtx.currentTime + timeElapsedSecs, 0.01)
osc.frequency.setTargetAtTime(noteData["pitch"], audioCtx.currentTime + timeElapsedSecs, 0.01)
osc.type = currentWaveform;
timeElapsedSecs += noteData["length"] / 10.0;
timings.gain.setTargetAtTime(0, audioCtx.currentTime + timeElapsedSecs, 0.01)
timeElapsedSecs += 0.2; //rest between notes
});
setTimeout(scheduleAudio, timeElapsedSecs * 1000);
}
function parseCode(code) {
//how could we allow for a repeat operation
//(e.g. "3@340 2[1@220 2@330]"" plays as "3@340 1@220 2@330 1@220 2@330")
//how could we allow for two lines that play at the same time?
//what if we want variables?
//how does this parsing technique limit us?
let notes = code.split(" ");
//notice this will fail if the input is not correct
//how could you handle this? allow some flexibility in the grammar? fail gracefully?
//ideally (probably), the music does not stop
notes = notes.map(note => {
noteData = note.split("@");
return {
"length": eval(noteData[0]), //the 'eval' function allows us to write js code in our live coding language
"pitch": eval(noteData[1])
};
//what other things should be controlled? osc type? synthesis technique?
});
return notes;
}
function genAudio(data) {
liveCodeState = data;
}
function reevaluate() {
var code = document.getElementById('code').value;
var data = parseCode(code);
genAudio(data);
}
playButton.addEventListener('click', function () {
if (!audioCtx) {
initAudio();
}
reevaluate();
});
// ref to dropdown for wave types
const waveformSelect = document.getElementById('waveform_select');
// adding listener to dropdown
waveformSelect.addEventListener('change', function () {
// update waveform variable when the selection changes
currentWaveform = this.value;
//log value
console.log('Waveform value:', currentWaveform);
});