我正在使用Expo Audio在组件中再现曲目,但当我关闭/更改屏幕时,音频仍在播放:如何解决此问题?
这是我使用CardAudio组件的核心组件。
const ObjectDetails = ({ route, navigation }) => {
return (
<View style={{ flex: 1, width, height, backgroundColor: '#fff' }}>
.
.
.
<CardAudio audioPath={oggetto.audioPath} />
</View >
)
}
export default ObjectDetails;
这是我的组件CardAudio,我在这里复制曲目。
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>
}
除了ObjectDetails屏幕之外,我还有一个名为Home的屏幕。当用户返回主屏幕而不按下按钮停止音频时,最后一次应该停止。
您必须清理useEfect((中的代码。由于这就是您构建代码的方式,只需在useEffectreturn
语句中添加清理代码即可。
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)
}
})()
// this function will be fired when you leave the page
return ()=>{
sound && sound.unloadAsync()
}
}, [audioStatus])