Attribute for duration on <audio> tags

Viewed 86

When working with <audio> tags I usually set the preload="metadata" in order to reduce bandwidth. Still this triggers a request on page load because the browser retrieves the duration of the file.

Is there a way to set the duration to an <audio> tag via an attribute? That way no request at all would be needed for the browser to display the duration prior to starting it. Something like:

<audio src="myfile.mp3" duration="600" preload="none">

Whereby 600 would be seconds.

1 Answers

This can be achieved by setting audio.src with bytes for an "empty" audio file. For example, an RIFF/WAV file could be created for your required duration, and the browser renders the duration time in the UI.

document.querySelectorAll('audio[data-duration]').forEach(initAudio)

function initAudio(audio) {
  // 0s 8-bit Mono Linear PCM 8000Hz WAV header
  const sampleRate = 8000
  const wavHeader = new Uint32Array([1179011410, 36, 1163280727, 544501094, 16, 65537, sampleRate, sampleRate, 524289, 1635017060, 0])

  const { duration, url } = audio.dataset

  // PCM8 WAV data
  const wavData = new Uint8Array(Math.ceil(duration * sampleRate))
  const dataSize = wavData.byteLength

  // set sizes
  wavHeader.set([dataSize + 36], 1)
  wavHeader.set([dataSize], 10)

  audio.src = URL.createObjectURL(new Blob([wavHeader, wavData]))

  // swap audio with url to play
  audio.addEventListener('play', () => {
    audio.src = url
    audio.play()
  }, { once: true })
}
<audio controls
  data-duration="15.13"
  data-url="https://opus-bitrates.anthum.com/audio/music-96.opus" />

Related