-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaudioManager.js
73 lines (62 loc) · 2.04 KB
/
audioManager.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
let backgroundAudio = null;
let isAudioPlaying = false;
let userInteracted = false;
const toggleAudio = () => {
if (isAudioPlaying) {
backgroundAudio.pause();
isAudioPlaying = false;
} else {
const playPromise = backgroundAudio.play();
if (playPromise !== undefined) {
playPromise.then(() => {
isAudioPlaying = true;
}).catch((error) => {
console.error('Playback failed:', error);
});
}
}
};
const playAudio = () => {
if (userInteracted) {
// Check if the audio is already playing
if (!backgroundAudio.paused && !backgroundAudio.ended && backgroundAudio.readyState > backgroundAudio.HAVE_CURRENT_DATA) {
return; // Do not call play() if the audio is already playing
}
const playPromise = backgroundAudio.play();
if (playPromise !== undefined) {
playPromise.then((success) => {
console.log(success)
isAudioPlaying = true;
}).catch((error) => {
console.error('Playback failed:', error);
});
}
}
};
// Resets the audio to the beginning
const restartAudio = () => {
backgroundAudio.currentTime = 0; // Make audio play from start
playAudio();
};
const mounted = () => {
backgroundAudio = document.getElementById('backgroundAudio');
backgroundAudio.addEventListener('play', () => {
isAudioPlaying = true;
});
backgroundAudio.addEventListener('pause', () => {
isAudioPlaying = false;
});
// Listen for the first user interaction
const handleFirstInteraction = () => {
if (!userInteracted) {
userInteracted = true;
playAudio();
// Remove the event listener after the first interaction
window.removeEventListener('click', handleFirstInteraction);
}
};
window.addEventListener('click', handleFirstInteraction);
};
document.addEventListener('DOMContentLoaded', () => {
mounted();
});