Gregory Schultz
Gregory Schultz

Reputation: 844

HTML5 duration time of MP3 sometimes works

I'm having problems showing the duration time of an MP3 file in my HTML5 audio player. Sometimes it will load the duration time, sometimes it won't.

The times it doesn't load is when I'm making changes to the CSS and when I refresh the page.

When I change the MP3 file to load another MP3 file, the duration time shows up. It goes away when I refresh the page.

This is the code for duration time:

audio.addEventListener('loadedmetadata', function(){
  progress.setAttribute('max', Math.floor(audio.duration));
  duration.textContent  = toHHMMSS(audio.duration);
});

I'm new at JavaScript so I have no idea how to code. I'm using this code from https://codepen.io/davatron5000/pen/uqktG and when you refresh the page, the duration of mp3 file disappears.

Upvotes: 0

Views: 1210

Answers (1)

Kaiido
Kaiido

Reputation: 136707

This is probably because of cache.

If you are setting your audio's src in the markup (html), the cached version of your media may already be loaded* when you attach the event listener.

Hence your event handler won't fire ever :

window.onload = function(){ // kinda force the situation

  aud.onloadedmetadata = function(e){  // this won't fire
    console.log('metatadata loaded');
    };
  };
<audio src="https://dl.dropboxusercontent.com/s/agepbh2agnduknz/camera.mp3" id="aud"/>

But in this case, you can already access its duration.
So you just have to check for its duration :

window.onload = function() {
  if (aud.duration) {
    doSomething();
  } else {
    aud.onloadedmetadata = doSomething;
  }
}

function doSomething(event) {
  console.log(aud.duration);
  console.log('from event handler :', !!event);
}
<audio src="https://dl.dropboxusercontent.com/s/agepbh2agnduknz/camera.mp3" id="aud" />

Or you can set again your media src in js.

window.onload = function() {
  aud.onloadedmetadata = function doSomething(event) {
    console.log(aud.duration);
  }

  aud.src = aud.src; // forces the event to fire again
}
<audio src="https://dl.dropboxusercontent.com/s/agepbh2agnduknz/camera.mp3" id="aud" />

*UAs have different behavior for this, e.g FF will store all the load events until all the inline scripts has been parsed. Safari and sometimes Chrome fire it as soon as they can.

Upvotes: 1

Related Questions