【问题标题】:Stop Audio expo-av - React Native ExpoStop Audio expo-av - React Native Expo
【发布时间】:2020-11-11 11:26:19
【问题描述】:

我在 react-native-expo 中使用来自 expo-av 的 Audio

我可以在 Audio.sound 构造器上使用 loadAsync 方法运行音频。

虽然当我试图停止声音时,它并没有停止声音。

以下是简约代码 sn-p。这是停止声音的正确方法吗?我无法找到解决方案。

import React, {useState,  useEffect} from 'react';
import {  Button } from 'react-native';
import { Audio } from 'expo-av';

export default function App() {
  const [audioStatus, setAudioStatus] = useState(false)
  const sound = new Audio.Sound();
  
  useEffect(()=>{
    (async () => {
            console.log('status', audioStatus)
            if (audioStatus) {
                await sound.loadAsync('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')
                try {
                    await sound.playAsync()
                } catch (e) {
                    console.log(e)
                }
            }else {
                await sound.stopAsync()
                await sound.unloadAsync()
            }
          })()
  },[audioStatus])
  
  return (
      <Button color={audioStatus ? 'red' : 'green'} title={'play'} onPress={()=>setAudioStatus(!audioStatus)} />
  );
}

提前致谢

【问题讨论】:

    标签: javascript react-native audio expo expo-av


    【解决方案1】:

    这是一个 React 问题。每次您的组件呈现时,sound 变量都会被重置为一个新的、尚未加载的 Audio.Sound 对象。这里,sound 应该是组件状态的一部分。你可以换行:

    const sound = new Audio.Sound();
    

    const [sound, setSound] = useState(new Audio.Sound());
    

    它会起作用的。

    Expo Snack

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-22
      • 2021-12-30
      • 2018-10-21
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 2020-03-15
      相关资源
      最近更新 更多