Expo-av library in RN not unloading sound when navigating to different screen

105 Views Asked by At

I am using expo-av library in order to play background sound for the 1st screen in my app (index.js) but the background sound keeps playing when I navigate to other screens.

I have followed the official docs from expo website but can't get it to work. I'd like it to stop playing the background sound when navigating to other screens. Feels like an Async problem but unsure as I am pretty new. Appreciate any help!

my code:

const BookSelection = () => {
      LogBox.ignoreLogs(['new NativeEventEmitter']); // Ignore log notification by message

      const [sound, setSound] = React.useState();

      async function playSound() {
        console.log('Loading Sound');
        const { sound } = await Audio.Sound.createAsync( require('../assets/audio/BackgroundMusic.mp3')
        );
        setSound(sound);
      
        console.log('Playing Sound');
        await sound.playAsync();
      }
      
      React.useEffect(() => {
        return sound
          ? () => {
              console.log('Unloading Sound');
              sound.unloadAsync();
            }
          : undefined;
      }, [sound]);

      return (
      <ImageBackground
        source={require('../assets/images/book1/page1.png')}
        style={styles.backgroundImage}
      >
          
          <View style={styles.container}>
          <Button title="Play Sound" onPress={playSound} />
            <FlatList
              data={booksData}
              renderItem={({item}) => <Book book = {item} />}
              showsVerticalScrollIndicator={false}
            />
            
          </View>
         
      </ImageBackground>
      
      );
    };
    
    const styles = StyleSheet.create({
      backgroundImage: {
        flex: 1,
        resizeMode: 'cover',
      },
      container: {
        flex: 1,
        paddingHorizontal: '5%',
        top: Constants.statusBarHeight,
        // backgroundColor: 'lightblue',
      },
    });
    
    
export default BookSelection;
1

There are 1 best solutions below

0
On

Hey if the sound is already playing (not still buffering) than it should be simply done like this

const navigation = useNavigation();
 useEffect(() => {
    const navigationUnsubscribe = navigation.addListener("blur", async () => {
        await sound.unloadAsync();
    });
    return () => {
        navigationUnsubscribe();
    };
}, [navigation]);

I have similar problem but when the sound is still buffering, then after switching naigationState (to another screen) it still loads in background and starts playing when it fully loads :)