iam having a problem in my app that i can play more than one audio at the same time and i want to prevent this behavior to only play one audio at time
here is my compponent that play the audio
const Box = ({ item, data }) => {
const [sound, setSound] = useState(); // State to hold the sound object
const [isPlaying, setIsPlaying] = useState(false);
// =================== playing audio ===================
useEffect(() => {
return sound
? () => {
sound.unloadAsync();
}
: undefined;
}, [sound]);
const playTrack = async () => {
if (sound) {
await sound.unloadAsync();
}
if (!item?.audio) {
return;
}
const { sound: newSound } = await Audio.Sound.createAsync({
uri: item.audio,
});
setSound(newSound);
newSound.setOnPlaybackStatusUpdate(onPlaybackStatusUpdate);
await newSound.playAsync();
};
const onPlaybackStatusUpdate = (status) => {
if (!status.isLoaded) {
return;
}
setIsPlaying(status.isPlaying);
};
const onPlayPause = async () => {
if (!sound) {
await playTrack();
} else if (isPlaying) {
await sound.pauseAsync();
} else {
await sound.playAsync();
}
};
return (
<View style={styles.container}>
<TouchableOpacity>
<Ionicons
onPress={onPlayPause}
disabled={!item.audio}
name={isPlaying ? "pause-outline" : "play-outline"}
size={24}
color={item.audio ? "#6961F8" : "gray"}
/>
</TouchableOpacity>
);
};
export default Box;
and this is its parent componenet i have tried to make state to track the audio from the parent but it didnt work
const TafseerDetails = ({ route }) => {
return (
<SafeAreaView style={styles.container}>
<StatusBar style="dark" />
<TouchableOpacity
style={styles.iconContainer}
activeOpacity={0.5}
onPress={() => navigation.goBack()}
>
<Image
style={styles.icon}
source={require("../assets/icons/arrow-left.png")}
resizeMode="contain"
/>
</TouchableOpacity>
<Card data={data} />
<Verses ayats={ayats} data={data} />
</SafeAreaView>
);
};
export default TafseerDetails;
const Verses = ({ ayats, data }) => {
return (
<View style={styles.container}>
<FlashList
estimatedItemSize={200}
data={ayats}
keyExtractor={(item) => item.number.toString()}
renderItem={({ item }) => <Box item={item} data={data}/>}
showsVerticalScrollIndicator={false}
contentContainerStyle={{ paddingBottom: 450 }}
ItemSeparatorComponent={() => (
<View
style={{
height: 1,
backgroundColor: "#f1f1f6",
marginVertical: 20,
marginHorizontal: 20,
}}
/>
)}
/>
</View>
);
};
export default Verses;