Skip to content

Commit 0a1c0ca

Browse files
committed
check for and resume audio context before triggering sounds
1 parent 0103202 commit 0a1c0ca

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

assets/js/sound_effect.js

+24-2
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,18 @@
22
* @type {{
33
* mounted: () => void,
44
* handleEvent: (event: string, callback: (payload: any) => void) => void
5+
* audioCtx: AudioContext,
6+
* audioCache: Record<string, AudioBuffer>,
57
* }}
68
*/
79
export const soundEffectHook = {
810
mounted() {
9-
console.log("time to hook up the sound effect!");
10-
1111
// Initialize Audio Context
1212
this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
13+
14+
// Try to resume AudioContext in case it's suspended
15+
this.resumeAudioContext();
16+
1317
// Cache for storing fetched sounds
1418
this.audioCache = {};
1519

@@ -19,8 +23,14 @@ export const soundEffectHook = {
1923
});
2024
},
2125

26+
/**
27+
* @param {string} url
28+
*/
2229
async playSound(url) {
2330
try {
31+
// Ensure the AudioContext is running
32+
await this.resumeAudioContext();
33+
2434
// Use cached sound if available, otherwise fetch, decode, and cache it
2535
if (!this.audioCache[url]) {
2636
// Fetch sound file
@@ -45,4 +55,16 @@ export const soundEffectHook = {
4555
source.connect(this.audioCtx.destination); // Connect to the output (speakers)
4656
source.start(0); // Play immediately
4757
},
58+
59+
/**
60+
* Checks for a suspended AudioContext and attempts to resume it
61+
*/
62+
async resumeAudioContext() {
63+
if (this.audioCtx.state === "suspended") {
64+
// Attempt to resume the AudioContext
65+
return this.audioCtx.resume();
66+
}
67+
// Return a resolved promise for consistency in asynchronous behavior
68+
return Promise.resolve();
69+
},
4870
};

0 commit comments

Comments
 (0)