@@ -17,17 +17,30 @@ const convertedSounds = [] as string[]
1717export async function loadSound ( path : string , contents = path ) {
1818 if ( loadingSounds . includes ( path ) ) return true
1919 loadingSounds . push ( path )
20- const res = await window . fetch ( contents )
21- if ( ! res . ok ) {
22- const error = `Failed to load sound ${ path } `
23- if ( isCypress ( ) ) throw new Error ( error )
24- else console . warn ( error )
25- return
26- }
27- const data = await res . arrayBuffer ( )
2820
29- sounds [ path ] = data
30- loadingSounds . splice ( loadingSounds . indexOf ( path ) , 1 )
21+ try {
22+ audioContext ??= new window . AudioContext ( )
23+
24+ const res = await window . fetch ( contents )
25+ if ( ! res . ok ) {
26+ const error = `Failed to load sound ${ path } `
27+ if ( isCypress ( ) ) throw new Error ( error )
28+ else console . warn ( error )
29+ return
30+ }
31+ const arrayBuffer = await res . arrayBuffer ( )
32+
33+ // Decode the audio data immediately
34+ const audioBuffer = await audioContext . decodeAudioData ( arrayBuffer )
35+ sounds [ path ] = audioBuffer
36+ convertedSounds . push ( path ) // Mark as converted immediately
37+
38+ loadingSounds . splice ( loadingSounds . indexOf ( path ) , 1 )
39+ } catch ( err ) {
40+ console . warn ( `Failed to load sound ${ path } :` , err )
41+ loadingSounds . splice ( loadingSounds . indexOf ( path ) , 1 )
42+ if ( isCypress ( ) ) throw err
43+ }
3144}
3245
3346export const loadOrPlaySound = async ( url , soundVolume = 1 , loadTimeout = 500 ) => {
@@ -53,13 +66,6 @@ export async function playSound (url, soundVolume = 1) {
5366 return
5467 }
5568
56- for ( const [ soundName , sound ] of Object . entries ( sounds ) ) {
57- if ( convertedSounds . includes ( soundName ) ) continue
58- // eslint-disable-next-line no-await-in-loop
59- sounds [ soundName ] = await audioContext . decodeAudioData ( sound )
60- convertedSounds . push ( soundName )
61- }
62-
6369 const soundBuffer = sounds [ url ]
6470 if ( ! soundBuffer ) {
6571 console . warn ( `Sound ${ url } not loaded yet` )
0 commit comments