-
Notifications
You must be signed in to change notification settings - Fork 0
/
delay.html
118 lines (96 loc) · 2.44 KB
/
delay.html
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
<html>
<head>
<title>NEJS 2016 - Delay</title>
<style>
body {
align-items: center;
display: flex;
flex-direction: column;
font-size: 30px;
height: 100%;
justify-content: center;
}
.buttons {
display: flex;
margin-top: 20px;
}
button {
font-size: 20px;
margin: 0 10px;
}
input[type="range"] {
font-size: 30px;
}
</style>
</head>
<body>
<p data-status>Decoding audio...</p>
<input
data-delay-slider
type="range"
value="0"
min="0"
max="1"
step=".01" />
<div class="buttons">
<button data-play>Play</button>
<button data-stop>Stop</button>
</div>
<script>
// create web audio context
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
// DOM nodes
const ui = {
'status': document.querySelector('[data-status]'),
'play': document.querySelector('[data-play]'),
'stop': document.querySelector('[data-stop]'),
'slider': document.querySelector('[data-delay-slider]'),
};
// create delay node
const delay = audioCtx.createDelay();
// create gain node for delay
const gainNode = audioCtx.createGain();
gainNode.gain.value = .7;
let bufferSource;
// fetch mp3
fetch('/assets/nejs.ogg')
// fetch as array buffer
.then(response => response.arrayBuffer())
// decode audio data from array buffer
.then(arrayBuffer => audioCtx.decodeAudioData(arrayBuffer))
.then(decodedAudio => {
ui.status.innerHTML = 'Audio decoded.';
// create buffer, start and connect to delay
// connect delay to output
ui.play.addEventListener('click', e => {
e.preventDefault();
// bufferSource already started
if (bufferSource) {
false;
}
// create new buffer, connect to output and play
bufferSource = audioCtx.createBufferSource();
bufferSource.buffer = decodedAudio;
bufferSource.loop = true;
bufferSource.connect(audioCtx.destination);
bufferSource.connect(delay);
delay.connect(gainNode)
gainNode.connect(audioCtx.destination);
bufferSource.start(0);
});
// stop buffer
ui.stop.addEventListener('click', e => {
e.preventDefault();
bufferSource.stop(0);
bufferSource = false;
});
});
// update delay time with slider
ui.slider.addEventListener('input', e => {
delay.delayTime.value = e.currentTarget.value;
});
console.log(audioCtx);
console.log(delay);
</script>
</body>
</html>