-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
71 lines (55 loc) · 1.76 KB
/
main.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
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioContext = new AudioContext();
const audioElement = document.querySelector("audio");
const track = audioContext.createMediaElementSource(audioElement);
// Select the play button
const playButton = document.querySelector("button");
playButton.addEventListener(
"click",
() => {
// Check if context is in suspended state (autoplay policy)
if (audioContext.state === "suspended") {
audioContext.resume();
}
// Play or pause track depending on state
if (playButton.dataset.playing === "false") {
audioElement.play();
playButton.dataset.playing = "true";
} else if (playButton.dataset.playing === "true") {
audioElement.pause();
playButton.dataset.playing = "false";
}
},
false,
);
//listens for end of song and stops audio
audioElement.addEventListener(
"ended",
() => {
playButton.dataset.playing = "false";
},
false,
);
//gain control (references gain range value from index.html)
const gainNode = audioContext.createGain();
const volumeControl = document.querySelector("#volume");
volumeControl.addEventListener(
"input",
() => {
gainNode.gain.value = volumeControl.value;
},
false,
);
// panning parameter (references panning range value from index.html)
const pannerOptions = { pan:0};
const panner = new StereoPannerNode(audioContext, pannerOptions);
const pannerControl = document.querySelector("#panner");
pannerControl.addEventListener(
"input",
() => {
panner.pan.value = pannerControl.value;
},
false,
);
// connecting all nodes together in order in series
track.connect(gainNode).connect(panner).connect(audioContext.destination)