Using Expo-av to play short sounds every second

Please provide the following:

  1. SDK Version: 44
  2. Platforms(Android/iOS/web/all): iOS
  3. Add the appropriate “Tag” based on what Expo library you have a question on.

I’m trying to use the Expo-AV module to play short audio clips and I’m not sure of the best way to load, unload and play them.

The app is a timer app that will play different sounds based on what time it is. For example, every 15 seconds, play “gong”, every minute, play “chime”, last 5 seconds, each second play “ding”.

Currently, I’m using a function like this, which is storing the “soundToPlay” in a global variable so that I can unload it. Not sure if that would be a memory leak if I didn’t.

I’m not sure if this is even close to the way you might approach this.

async function playSound(whichSoundtoPlay: AssetNames) {
  if (soundToPlay) {
    soundToPlay.unloadAsync();
  }
  const { sound } = await Audio.Sound.createAsync(alertSounds[whichSoundtoPlay]);
  // await sound.unloadAsync();
  soundToPlay = sound;
  await soundToPlay.playAsync();
}

I’m open to any ideas!

Thanks!

Hi,

I think loading and unloading the sounds every time is suboptimal. You can load the sound object once at startup and cache it in some variable, then just call playAsync() multiple times, e.g. in setInterval().
Your problem puzzled me so I made a quick example on Snack: timer sound - Snack
It’s not perfect, but it shows the basic idea.

Just note that due to some web limitations of Snack, you may need to click on the app screen for the browser to start playing sound.

Thank you! Your example made a lot of sense and helped immensely!

I’m thinking I will use Expo’s AppLoading component to do the initial caching of the sounds.

Thanks again!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.