-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
executable file
·72 lines (65 loc) · 2.27 KB
/
script.js
File metadata and controls
executable file
·72 lines (65 loc) · 2.27 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
document.querySelectorAll('.audio-player').forEach(createAudioPlayer);
function createAudioPlayer(audioPlayer) {
const url = audioPlayer.dataset.song;
const audio = new Audio(url);
console.log({ audio, audioPlayer, url });
audio.addEventListener(
'loadeddata',
() => {
audioPlayer.querySelector('.time .length').textContent =
getTimeCodeFromNum(audio.duration);
audio.volume = 1.0;
},
false
);
//click on timeline to skip around
const timeline = audioPlayer.querySelector('.timeline');
timeline.addEventListener(
'click',
(e) => {
const timelineWidth = window.getComputedStyle(timeline).width;
const timeToSeek =
(e.offsetX / parseInt(timelineWidth)) * audio.duration;
audio.currentTime = timeToSeek;
},
false
);
//check audio percentage and update time accordingly
setInterval(() => {
const progressBar = audioPlayer.querySelector('.progress');
progressBar.style.width =
(audio.currentTime / audio.duration) * 100 + '%';
audioPlayer.querySelector('.time .current').textContent =
getTimeCodeFromNum(audio.currentTime);
}, 500);
//toggle between playing and pausing on button click
const playBtn = audioPlayer.querySelector('.controls .toggle-play');
playBtn.addEventListener(
'click',
() => {
if (audio.paused) {
playBtn.classList.remove('play');
playBtn.classList.add('pause');
audio.play();
} else {
playBtn.classList.remove('pause');
playBtn.classList.add('play');
audio.pause();
}
},
false
);
//turn 128 seconds into 2:08
function getTimeCodeFromNum(num) {
let seconds = parseInt(num);
let minutes = parseInt(seconds / 60);
seconds -= minutes * 60;
const hours = parseInt(minutes / 60);
minutes -= hours * 60;
if (hours === 0)
return `${minutes}:${String(seconds % 60).padStart(2, 0)}`;
return `${String(hours).padStart(2, 0)}:${minutes}:${String(
seconds % 60
).padStart(2, 0)}`;
}
}