0

我正在使用 react-native-sound 创建音频播放器,我想在播放时获取声音的当前播放时间,但是当我使用 getCurrentTime 回调时,它只显示 0。下面是相同的代码:

const listenaudio = (audio, id) => {
    console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
    if (playAudio != null) {
      playAudio.release();
    }

    setsoundpause(id);
    playAudio = new Sound(audio, Sound.MAIN_BUNDLE, (error) => {
      console.log("rrr")
      if (error) {
        return;
      }
      // loaded successfully
      // Play the sound with an onEnd callback
      playAudio.play((success) => {
        if (success) {
          setsoundpause(0);
        } else {
        }
      });
    });
    playAudio.setVolume(1);   
    playAudio.getCurrentTime((seconds) => console.log('at ' + seconds));  // here
  };

如果有人能建议我该怎么做,那就太好了?我应该使用 seInterval() 吗?任何线索将不胜感激。

4

1 回答 1

0

我最近使用 react-native-sound 制作了一个播放器,我在几毫秒后调用 getCurrentTime 方法来获取实时播放器时间。

我播放音频的功能

const timerRef = React.useRef();

const playSound = () => {
    // Sound.MAIN_BUNDLE
    try {
      if (!playAudio || !playAudio.isLoaded()) return;

      if (timerRef.current) clearInterval(timerRef.current);
      timerRef.current = setInterval(() => {
        playAudio.getCurrentTime((seconds, isPlaying) => {
          setCurrentPlayTime(seconds); // HERE is time of current player
        });
      }, 300);    

      playAudio.play(success => {
        if (!success) {
          console.log('playback failed due to audio decoding errors');
        }
        stopSound();
      });

    } catch (err) {
      console.log("can't play voice message", err);
    }
  };
于 2021-05-02T17:29:00.347 回答