2
2
* @type {{
3
3
* mounted: () => void,
4
4
* handleEvent: (event: string, callback: (payload: any) => void) => void
5
+ * audioCtx: AudioContext,
6
+ * audioCache: Record<string, AudioBuffer>,
5
7
* }}
6
8
*/
7
9
export const soundEffectHook = {
8
10
mounted ( ) {
9
- console . log ( "time to hook up the sound effect!" ) ;
10
-
11
11
// Initialize Audio Context
12
12
this . audioCtx = new ( window . AudioContext || window . webkitAudioContext ) ( ) ;
13
+
14
+ // Try to resume AudioContext in case it's suspended
15
+ this . resumeAudioContext ( ) ;
16
+
13
17
// Cache for storing fetched sounds
14
18
this . audioCache = { } ;
15
19
@@ -19,8 +23,14 @@ export const soundEffectHook = {
19
23
} ) ;
20
24
} ,
21
25
26
+ /**
27
+ * @param {string } url
28
+ */
22
29
async playSound ( url ) {
23
30
try {
31
+ // Ensure the AudioContext is running
32
+ await this . resumeAudioContext ( ) ;
33
+
24
34
// Use cached sound if available, otherwise fetch, decode, and cache it
25
35
if ( ! this . audioCache [ url ] ) {
26
36
// Fetch sound file
@@ -45,4 +55,16 @@ export const soundEffectHook = {
45
55
source . connect ( this . audioCtx . destination ) ; // Connect to the output (speakers)
46
56
source . start ( 0 ) ; // Play immediately
47
57
} ,
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
+ } ,
48
70
} ;
0 commit comments