0

我正在使用 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 的屏幕。当用户返回主屏幕而不按按钮停止音频时,最后一个应该停止。

4

1 回答 1

0

您必须清理 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])
于 2021-08-02T22:50:43.083 回答