-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio-buffer-decode-audio.html
84 lines (70 loc) · 1.76 KB
/
audio-buffer-decode-audio.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
<html>
<head>
<title>NEJS 2016 - Audio Buffer Decode Audio</title>
<style>
body {
align-items: center;
display: flex;
flex-direction: column;
font-size: 20px;
height: 100%;
justify-content: center;
}
.buttons {
display: flex;
}
button {
font-size: 30px;
margin: 0 10px;
}
</style>
</head>
<body>
<p data-status>Decoding audio...</p>
<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]'),
};
let bufferSource;
// fetch mp3
fetch('/assets/digitalsurgeons.mp3')
// 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 output
ui.play.addEventListener('click', e => {
e.preventDefault();
// buffer already started
if (bufferSource) {
false;
}
// create new buffer, connect to output and play
bufferSource = audioCtx.createBufferSource();
bufferSource.buffer = decodedAudio;
bufferSource.connect(audioCtx.destination);
bufferSource.start(0);
});
// stop buffer
ui.stop.addEventListener('click', e => {
e.preventDefault();
bufferSource.stop(0);
bufferSource.disconnect();
bufferSource = false;
});
});
console.log(audioCtx);
</script>
</body>
</html>