-
Notifications
You must be signed in to change notification settings - Fork 8
/
audio.js
91 lines (70 loc) · 1.92 KB
/
audio.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
import * as basic from "./basic.js";
export var synth;
export var currentBpm;
export var currentVolume;
export var ttsUtterance = "speechSynthesis" in window ? new SpeechSynthesisUtterance() : null;
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
export function beatsToMilliseconds(bpm = currentBpm) {
return (60 * 1000) / bpm;
}
export function setEnvelope(attack, decay, sustain, release) {
synth.set({
envelope: {
attack: Math.max(attack, 0) / 1000,
decay: Math.max(decay, 0) / 1000,
sustain: clamp(sustain, 0, 1),
release: Math.max(release, 0) / 1000
}
});
}
export function setVolume(amount) {
currentVolume = amount;
synth.volume.value = 20 * Math.log10(clamp(amount, 0, 1));
if (ttsUtterance != null) {
ttsUtterance.volume = clamp(amount, 0, 1);
}
}
export function setVoice(pitch, rate) {
if (ttsUtterance == null) {
return;
}
ttsUtterance.pitch = pitch;
ttsUtterance.rate = rate;
}
export function setBpm(bpm) {
currentBpm = bpm;
}
export function play(note, beats = 1) {
var frequency = new Tone.Frequency(note).toFrequency();
if (Number.isNaN(frequency)) {
throw new basic.RuntimeError("Invalid note");
}
synth.triggerAttackRelease(frequency, (beatsToMilliseconds() * beats) / 1000);
}
export function quiet() {
synth.releaseAll();
speechSynthesis.cancel();
}
export function speak(message) {
if (ttsUtterance == null) {
return;
}
ttsUtterance.text = message;
speechSynthesis.cancel();
speechSynthesis.speak(ttsUtterance);
}
export function init() {
setEnvelope(100, 200, 0.5, 800);
setVolume(1);
setVoice(1, 1);
setBpm(120);
}
window.addEventListener("load", function() {
if (window.inDocsPopout) {
return;
}
synth = new Tone.PolySynth().toDestination();
init();
});