I am using Expo Audio to reproduce a track in a component, but when i close/change the screen the audio is still playing: How can I solve this problem?
Here is my Core component where I use the CardAudio component.
const ObjectDetails = ({ route, navigation }) => {
return (
<View style={{ flex: 1, width, height, backgroundColor: '#fff' }}>
.
.
.
<CardAudio audioPath={oggetto.audioPath} />
</View >
)
}
export default ObjectDetails;
Here is my component CardAudio where i reproduce the track.
const CardAudio = (props) => {
const audioPath = props.audioPath;
const [sound, setSound] = useState(new Audio.Sound());
const [audioStatus, setAudioStatus] = useState(false);
const [flagAudio, setFlagAudio] = useState(true);
useEffect(() => {
(async () => {
console.log('status', audioStatus)
if (audioStatus) {
await sound.loadAsync({ uri: `url to get the audio file`/${audioPath} })
try {
await sound.playAsync();
setFlagAudio(false)
} catch (e) {
console.log(e)
}
} else if (audioStatus == false && flagAudio == false) {
await sound.stopAsync()
await sound.unloadAsync()
setFlagAudio(true)
}
})()
}, [audioStatus])
return <View style={styles.cardStats}>
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={styles.titolo}>Descrizione Audio</Text>
<TouchableOpacity onPress={() => {
setAudioStatus(!audioStatus)
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light)
}}>
{
audioStatus == true
? <AntDesign name="pausecircleo" size={SIZE / 2} color={'black'} />
: <AntDesign name="sound" size={SIZE / 2} color={'black'} />
}
</TouchableOpacity>
</View>
</View>
}
In addition to the ObjectDetails screen i have another screen called Home. When the user come back to the Home screen without pressing the button to stop the audio, this last should stop.