Home > database >  Update position of seeker (i.e html input type range) while an audio is playing
Update position of seeker (i.e html input type range) while an audio is playing

Time:02-21

I want the range slider automatically change while audio play.

<input type="range" name="seek" id="seeker" min="0" max="100" value="0" > 

let music = new Audio('https://www.computerhope.com/jargon/m/example.mp3');
music.play();
<input type="range" name="seek" id="seeker" min="0" max="100" value="0" > 

CodePudding user response:

Since new Audio() actually creates a new <audio> element (it is just not injected into your DOM), you can still listen to DOM events. For your use-case, you will want to listen to the timeupdate event, and get the progress of the play through by dividing the total duration of the audio clip with currentTime:

music.addEventListener('timeupdate', () => {
  const percent = music.currentTime / music.duration * 100;
  seeker.value = percent;
});

However, if you want the users to use the <input> element to seek through the audio clip (I assumed that since you named your element #seeker), then you will also need to listen to the input event from the element. You can use simple math to calculate what currentTime value you have to set on the audio element.

Here is a proof-of-concept example. I have ensured that play() is only triggered by a button click, since most browsers do not autoplay audio files today.

const music = new Audio('https://www.computerhope.com/jargon/m/example.mp3');
const seeker = document.querySelector('#seeker');

music.addEventListener('timeupdate', () => {
  const percent = music.currentTime / music.duration * 100;
  seeker.value = percent;
});

// Allow seeking
seeker.addEventListener('input', (e) => {
  music.currentTime = e.target.value / 100 * music.duration;
});

document.querySelector('#play-button').addEventListener('click', () => {
  music.play();
});
<input type="range" name="seek" id="seeker" min="0" max="100" value="0">
<button type="button" id="play-button">Play</button>

  • Related