I have 3 screens, A
, B
and C
. On B, I have an audio autoplaying. I have a Header which allows me to go forward to C or backward to A.
I have tried the code below. While the sound does stop when going B->C, when I go B->A it doesn't pause no matter what I tried.
App.tsx
<Stack.Navigator
screenOptions={{ headerShown: false }}>
<Stack.Screen name="Debug" component={A} />
<Stack.Screen name="Detail" component={B} />
<Stack.Screen name="All" component={C} />
</Stack.Navigator>
B.tsx
useEffect(() => {
if (Platform.OS === 'ios') {
enableAudio();
}
if (isFocused === true) {
console.log('play')
playSound();
} else if (isFocused === false) {
console.log('stop')
pauseSound();
}
return () => {
pauseSound()
}
}, [isFocused]);
useEffect(() => {
// ...
const unsubscribe = navigation.addListener('blur', () => {
console.log('blur');
pauseSound();
});
return unsubscribe;
}, []);
const playSound = async () => {
if (sound) {
await sound.playAsync();
}
else {
console.log('Loading Sound');
const { sound } = await Audio.Sound.createAsync(require('./../../assets/audio/001.ios.m4a'), { shouldPlay: true });
setSound(sound)
console.log('Playing Sound');
await sound.playAsync();
}
}
const pauseSound = async () => {
if (sound) {
console.log('Pausing Sound');
await sound.pauseAsync();
}
}
return (
<View>
<Header/>
...
</View>
)
Header.tsx
const navigation = useNavigation();
return(
<View style={styles.container}>
<TouchableOpacity onPress={() => { navigation.goBack() }}>
<Image
source={require('../../assets/icons/back_arrow.png')}
style={{ height: 38, width: 19 }}/>
</TouchableOpacity>
...
</View>
)