expo-audio codes difference

I am trying to play audio file and one set of code is playing the file but the second set of code is not playing. Actually, I followed and took the codes from https://docs.expo.io/versions/v38.0.0/sdk/audio/ .

Code that is working and playing correct audio file:

try {
        let soundFile = FileSystem.cacheDirectory + `sound/${data.banner_sound}`;
        const { sound: soundObject, status } = await Audio.Sound.createAsync(
          { uri: soundFile },
          { shouldPlay: true }
        );
        // Your sound is playing!
      } catch (error) {
        // An error occurred!
      }

Code that is not playing any sound and doesn’t have any error too:

      const soundObject = new Audio.Sound();
      try {        
        let soundFile = FileSystem.cacheDirectory + `sound/${data.banner_sound}`;
        await soundObject.loadAsync({ uri: soundFile });
        await soundObject.playAsync();
        // Your sound is playing!

        // Don't forget to unload the sound from memory
        // when you are done using the Sound object
        await soundObject.unloadAsync();
      } catch (error) {
        // An error occurred!
      }

Can anyone explain what is the difference between those two sets of codes? Thanks!

Found the reason. unloadAsync() is calling in second set of codes immediately after playAsync. Hence, the sound stops before it is even started. So, we will need to call unload in componentunmount or useeffect’s return function to clean up the resource.

1 Like

Glad you got things figured out! Good luck with your project moving forward.

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