如何使用Expo-Audio或Expo-av暂停音频

时间:2019-11-27 18:53:37

标签: react-native audio expo

以下代码的作用是播放加载到源中的音频,然后在isPlaying === true时应暂停音频。

假设DashboardItem中有数据传入其中,并且所有正确的Audio.setAudioModeAsync()数据都在componentDidMount()内被调用

{latestEP.docs.map(doc => (
    DashboardItem key={doc.id} doc={doc}/>
))}

我的问题是,它可以完美播放音频,但是当我尝试暂停音频时,我会收到以下错误消息:

pause error log = TypeError: playbackInstance.pauseAsync is not a function. (In 'playbackInstance.pauseAsync()', 'playbackInstance.pauseAsync' is undefined)
current state of (isPlaying) true current state of (playbackInstance) [object Object]

Ps。拥有1500或以上声誉的人是否可以为expo-audio制作标签,一直看到有关expo-audio的问题日志,因此值得使用。

const DashboardItem = observer(({ doc }) => {
  const { name, id, date, url, description } = doc.data;

  const [isPlaying, setIsPlaying] = useState(false);
  const [playbackInstance, setPlaybackInstance] = useState(null);
  const [volume, setVolume] = useState(1.0);
  const [isBuffering, setIsBuffering] = useState(true);

  const status = {
    shouldPlay: isPlaying,
    volume: volume
  };

  handleAudio = async url => {
    const source = {
      uri: url
    };

    if (isPlaying === false) {
      try {
        const playbackInstance = new Audio.Sound();
        playbackInstance.setOnPlaybackStatusUpdate(this.onPlaybackStatusUpdate);
        await playbackInstance.loadAsync(source, status, true);
        await playbackInstance.playAsync()

        setPlaybackInstance({
          playbackInstance
        })
        setIsPlaying(!isPlaying);

        console.log(`playAsync() ran successfully`);
      } catch (error) {
        console.log(`play error log = ${error}`);
      }
    } else {
      try {
        await playbackInstance.pauseAsync();
        console.log(`pauseAsync() ran successfully`);
      } catch (error) {
        console.log(`pause error log = ${error}`);
        console.log(`current state of (isPlaying) ${isPlaying}`);
        console.log(`current state of (playbackInstance) ${playbackInstance}`);
      }
    }
  };

  onPlaybackStatusUpdate = status => {
    setIsBuffering(status.isBuffering);
  };

0 个答案:

没有答案