'Expo display remaining seconds of audio

I want to display how much seconds are left from the audio. Like this:

enter image description here

I know I need to use the positionMillis and thedurationMillis props, but how can I monitor the positionMillis?

When I click on a button I load the audio and play it (handleAudio function) . This was I will only get the positionMillis one time (or if I pause/resume the audio). How can I continuously watch the positionMillis prop of the audio?

const [sound, setSound] = useState(null);
const [soundStatus, setSoundStatus] = useState({ status: null, icon: play });

  async function handleAudio() {
    //playing audio for the first time
    if (soundStatus.status === null) {
      console.log("Loading Sound");
      const { sound, status } = await Audio.Sound.createAsync(
        {
          uri: `some_url`,
        },
        { shouldPlay: true },
        );
      setSound(sound);
      setSoundStatus({ status: status, icon: pause });
    }

    //pause audio
    if (soundStatus.status) {
      if (soundStatus.status.isLoaded && soundStatus.status.isPlaying) {
        const status = await sound.pauseAsync();
        console.log("pausing audio");
        setSoundStatus({ status: status, icon: play });
      }

      //resuming audio
      if (soundStatus.status.isLoaded && !soundStatus.status.isPlaying) {
        const status = await sound.playAsync();
        console.log("resuming audio");
        setSoundStatus({ status: status, icon: pause });
      }
    }
  }

<Button title="Play sound" onPress={handleAudio}/>
<Text> `${soundstatus.status.positionMillis}:${soundstatus.status.durationMillis}` </Text>


Solution 1:[1]

  const { sound, status } = await Audio.Sound.createAsync(
    {
      uri: `some_url`,
    },
    { shouldPlay: true },
    (status) => console.log(status.positionMilis),
  );

The Audio.Sound.createAsync takes a third argument which is a callback that is executed every 100ms for example (it can be changed). It is called with a status object that has everything you need. You can read more here

Solution 2:[2]

const [duration, setDuration] = useState(0);
    
Audio.setOnPlaybackStatusUpdate(()=>setDuration(status.positionMilis);

playbackObject.setOnPlaybackStatusUpdate(onPlaybackStatusUpdate);

Sets a function to be called regularly with the AVPlaybackStatus of the playbackObject

i know this might be a month late, use setOnPlaybackStatusUpdate as stated above

search expo documentation for setOnplaybackStatusUpdate

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oro
Solution 2 D J