How to unload Audio the right way?

I just wanted to know how to unload an audio after it has finished playing. The documentation was a bit confusing.

This causes the audio not to play

  async clickSound() {
   const soundObject = new Expo.Audio.Sound();
    try {
      await soundObject.loadAsync(loadedClickSound);
      await soundObject.playAsync();
      await soundObject.unloadAsync();
    } catch (error) {
    }
  }

Also if I were unload a audio files from another page could I do it without passing props like this, where clicksound is a audio file. Will this clear clear all the specific sounds from the memory

  async unloadSound() {
   const soundObject = new Expo.Audio.Sound();
    try {
      await soundObject.unloadAsync(ClickSound);
    } catch (error) {
    }
  }
1 Like

Unloading stops a Sound. You need to unload the Sound only after it’s done being used. In your first snippet you unload it immediately after starting to play it, which stops it, so you don’t hear anything.

Regarding your second question, store the reference to the Sound object somewhere then call .unloadAsync() on it.

@nikki How can I do that I’ve tried using getplaybackstatus but that always returns false.

https://docs.expo.io/versions/v26.0.0/sdk/audio#onplaybackstatusupdate-function----a-function-taking-a – this callback lets you listen for playback status changes, returning a https://docs.expo.io/versions/v26.0.0/sdk/av#playbackstatusthis-is-the-structure-returned-from-all. On !(shouldPlay || isPlaying), you could .unloadAsync() it.

Note that your application may want to play a Sound again. In general it may make sense for you to unload the sound after you are sure you won’t have to play it again, rather than every time it is stopped.

2 Likes

@nikki Thanks for your help :slight_smile:

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