当我移至下一个屏幕时如何停止声音播放器

问题描述 投票:0回答:1

每当我移动到应用程序中的下一个屏幕时,我想停止声音播放器。

const [shallPlay, setPlay] = useState(true);

useEffect(() =\> {
if (shallPlay) {
try {
SoundPlayer.playSoundFile("om_namo`your text`\_venkateshaya", ".mp3");
} catch (e) {
console.log(`cannot play the sound file`, e);
}
} else {
SoundPlayer.stop();
}
}, \[shallPlay\]);

\<TouchableOpacity
onPress={() => {
setPlay(!shallPlay);
}}
>

我是原生反应新手。找不到解决办法

react-native react-hooks
1个回答
0
投票

您可以使用

useFocusEffect

从'@react-navigation/native'导入{useFocusEffect};

const [shallPlay, setPlay] = useState(true);

useEffect(() => {
  if (shallPlay) {
    try {
      SoundPlayer.playSoundFile('om_namo_venkateshaya', '.mp3');
    } catch (e) {
      console.log('cannot play the sound file', e);
    }
} else {
  SoundPlayer.stop();
}   }, [shallPlay]);

useFocusEffect(
   React.useCallback(() => {
     // This will run when the screen is focused

  return () => {
    // This will run when the screen is unfocused
    // Stop the sound player when navigating away
    SoundPlayer.stop();
  };
}, [])   );
© www.soinside.com 2019 - 2024. All rights reserved.