mistymints
mistymints

Reputation: 43

How do I link my seek slider with the audio player in HTML?

I am making a Chrome extension that involves multiple audio players. I currently have play buttons that work for each individual audio, and I have also made the dummy version of a seek slider. I would like to link the audio with the slider so that I can control the progress of the audio and also see the time. Here is what I have now:

popup.js

const manageAudio = (audio) => {
  const playButton = audio.nextElementSibling;
  let isPlaying = false;
  audio.onplaying = function () {
    isPlaying = true;
  };
  audio.onpause = function () {
    isPlaying = false;
  };
  playButton.addEventListener("click", function () {
    if (isPlaying) {
      audio.pause();
    } else {
      audio.play();
    }
  })
  $(playButton).click(function () {
    $(playButton).toggleClass("paused");
  });
};

$(document).ready(function () {
  for (const audio of $('audio')) {
    manageAudio(audio);
  }
});

popup.html

<audio src=".../...mp3" type="audio/mp3"></audio>
<div class="play"></div>
<div class="controls">
    <input type="range" value="0" class="slider">
    <p>0:00</p>
    <p class="endtime">3:25</p>
</div>

The page looks like this:

what the page looks like

Any help would be greatly appreciated!!

Upvotes: 0

Views: 1155

Answers (1)

Utmost Creator
Utmost Creator

Reputation: 1121

Recommendations:

set the min value for range input to 0; do a check if an audio can be played by checking oncanplay (find more here);

Steps to be taken to at least reach some point

  1. get the tracktime (in seconds);
  2. set the maximun value for a range input to the total tracktime (duration - in seconds);
  3. then using ontimeupdate you can get either a current playing time or set the slider's value (for more info please take a look here;
  4. to update the slider you can get the current time (currentTime) of a track and set this value to the range input.

So, you just need to track update events on slider and audio, and after any of these changes, you will take action to update one or another source.

audio.currentTime = 30; // where audio is your audio object; 30 is 30th second of your track

Please let me know whether this is enough for you to continue

How to set audio position? (see here)

Upvotes: 4

Related Questions