javascript – Finish 10 sec. before, audio playback

Question:

In this example I want to show how using x.currentTime = 10; the audio takes the 10-second position and starts playing right from that point. My question is, how can it be done the other way around, that the audio ends 10 seconds before ?, since no documentation is found in this regard. Thankful in advance for your patience and wisdom.

var x = document.getElementById("myAudio");
function getCurTime() { 
  alert(x.currentTime);
} 

function setCurTime() { 
  x.currentTime = 10;
}
<audio id="myAudio" controls>
  <source src="https://freesound.org/data/previews/469/469273_4397472-lq.mp3" type="audio/mpeg">
</audio><br>

<button onclick="setCurTime()" type="button">Establecer la posición de inicio a 10 segundos</button>

Answer:

The media elements (audio and video) have the duration attribute , which you can use to calculate what you want:

On the other hand, you have the timeupdate event, which is timeupdate every time currentTime is updated by the browser.

I have taken your example, I have made the button go to 15 seconds from the end and then I have put an event listener to stop 5 seconds later, to see if it works for you.

var audio = document.getElementById("myAudio");
function setCurTime() { 
  audio.currentTime= audio.duration - 15;
}

audio.addEventListener('timeupdate', (event) => {
  if (audio.currentTime > (audio.duration - 10)) {
    audio.pause();
    console.log('Pausado!');
  }
});
<audio id="myAudio" controls>
  <source src="https://freesound.org/data/previews/469/469273_4397472-lq.mp3" type="audio/mpeg">
</audio><br>

<button onclick="setCurTime()" type="button">Establecer la posición de inicio a 15 segundos del final</button>
Scroll to Top