1

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>
Tyler Joe
  • 357
  • 2
  • 18

2 Answers2

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

Oro
  • 2,250
  • 1
  • 6
  • 22
Alex Popov
  • 69
  • 1
  • 3
0
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

D J
  • 845
  • 1
  • 13
  • 27
Preye
  • 39
  • 1
  • 5