Change Current Time Audio React JS

Change Current Time Audio React JS

In this post how to change time Audio on React JS, so you can jump the time of Audio to specific time, and of course you can jump while Audio is playing.

For first will using useRefuseRef if for access DOM node on a component, so we will using useRef for access Audio component like this

import { useRef } from 'react';

function AudioJump() {
  const audioRef = useRef(null);

  return (
    <>
      <audio ref={audioRef} controls>
        <source src="YOUR_MUSIC_URL" type="audio/mp3" />
        Your browser does not support the audio element.
      </audio>
    </>
  );
}

export default AudioJump;

Now we can access audio DOM node component, change YOUR_MUSIC_URL to music URL you want to play, now we will create button for jump.

<button onClick={() => changeCurrentTime(30)}>Jump To 30 Second</button>

And now create function for jump the time, in this example i will named the function is changeCurrentTime and i will jump to 30 second

const changeCurrentTime = (time) => {

    if (audioRef.current) {

      audioRef.current.currentTime = time;

    }

  };

In the code above we make sure audio component accessed, and then we the change time of audio with audioRef.current.currentTime = time, play audio and press jump button.

This for full code

Thanks for reading this post, if you have question or feedback, you can send message in Contact

Post a Comment

0 Comments