react-native-sound always showing current playback time as 0

1.4k Views Asked by At

I am using react-native-sound to create an audio player, I want to get the current playback timings of the sound while it plays however when I use the getCurrentTime callback, it is only showing 0. Below is the code for the same:

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
  };

It would be great if anyone could suggest how should I do it? Should I use seInterval() ? Any leads would be appreciated.

1

There are 1 best solutions below

2
On

I've made a player recently using react-native-sound, where I call getCurrentTime method after some milliseconds to get realtime player time.

My function to play audio

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);
    }
  };