Search code examples
javascriptjqueryhtml5-audio

How to set the duration of audio


I am trying to set the duration of an audio tag using HTML DOM duration property of audio.

I have tried the following but it doesn't seem to work: $('audio')[0].duration = 1;

I've gone through other answers but I couldn't see any which make use of the duration property.

If the duration property is readonly, what other method does it leave me with?


Solution

  • You cannot change the duration as it is locked to the original data (which cannot be changed via the audio element).

    You can achieve the illusion of a different duration though by making restrictions on play by monitoring the time and pause the audio when a threshold kicks in:

    • Use the timeupdate event and check currentTime against your threshold
    • You can also use requestAnimationFrame to poll the same value and do the same check
    • Or, for super-accurate timing, you need to use Web Audio API, create an audio-buffer for the audio, then use start/stop with the preferred times. This will require CORS requirements to be fulfilled

    On the loading side the browser will possibly load the entire file. If you want to control this part you would have to use Media Source Extension which allow you to control the buffering process.