[Solved] html5 display audio currentTime

I would like to display the current time of of an html 5 audio element and the duration of that element. I’ve been looking over the internet but can’t find a functional script which allows me to display how long the audio files is and what the time currently is e.g. 1:35 / 3:20.

Any one got any ideas :)?

Solution #1:

Here’s an example:

<audio id="track" src="http://upload.wikimedia.org/wikipedia/commons/a/a9/Tromboon-sample.ogg"
       ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime) + ' / ' + Math.floor(this.duration);">
    <p>Your browser does not support the audio element</p>
</audio>
<span id="tracktime">0 / 0</span>
<button onclick="document.getElementById('track').play();">Play</button>

This should work in Firefox and Chrome, for other browsers you’ll probably need to add alternative encodings.

Respondent: robertc

Solution #2:

here is simple usage. keep in mind html5 elements are still in the works so anything can change:

    audio = document.getElementsByTagName("audio")[0];

    //functions
    audio.load();
    audio.play();
    audio.pause();

    //properties
    audio.currentSrc  
    audio.currentTime  
    audio.duration

here is the reference HTML5 Audio

to get the currentTime while audio is playing you must attach the timeupdate event and update your current time within the callback function.

simple tutorial audio/video html5 on dev.opera

Solution #3:

robertc’s version will work fine except for the fact that it does not turn the number of seconds you get from math.floor() into proper time values.

Here is my function called when ontimeupdate is called:

<audio id='audioTrack' ontimeupdate='updateTrackTime(this);'>
  Audio tag not supported in this browser</audio>
<script>
function updateTrackTime(track){
  var currTimeDiv = document.getElementById('currentTime');
  var durationDiv = document.getElementById('duration');

  var currTime = Math.floor(track.currentTime).toString(); 
  var duration = Math.floor(track.duration).toString();

  currTimeDiv.innerHTML = formatSecondsAsTime(currTime);

  if (isNaN(duration)){
    durationDiv.innerHTML = '00:00';
  } 
  else{
    durationDiv.innerHTML = formatSecondsAsTime(duration);
  }
}
</script>

I modified formatSecondsAsTime() from something I found here:

function formatSecondsAsTime(secs, format) {
  var hr  = Math.floor(secs / 3600);
  var min = Math.floor((secs - (hr * 3600))/60);
  var sec = Math.floor(secs - (hr * 3600) -  (min * 60));

  if (min < 10){ 
    min = "0" + min; 
  }
  if (sec < 10){ 
    sec  = "0" + sec;
  }

  return min + ':' + sec;
}
Respondent: KStensland

Solution #4:

When you use audio.duration(). It will give you result in seconds. You just have to change this in minutes and seconds. Demo of Code is here, hope it will help you.

song.addEventListener('timeupdate',function (){

    var duration = song.duration; //song is object of audio.  song= new Audio();

    var sec= new Number();
    var min= new Number();
     sec = Math.floor( duration );    
     min = Math.floor( sec / 60 );
    min = min >= 10 ? min : '0' + min;    
    sec = Math.floor( sec % 60 );
    sec = sec >= 10 ? sec : '0' + sec;

    $("#total_duration").html(min + ":"+ sec);   //Id where i have to print the total duration of song.

    });

This code will definitely work for total duration. To get current Time, you just have to use song.currentTime; in place of song.duration;
Whole code will remain same.

Respondent: Anuj Sharma

Solution #5:

ES6

       const audio = new Audio();
       audio.src = document.querySelector('#audio').src;
       audio.play();
       audio.addEventListener('timeupdate', (event) => {
            const currentTime = Math.floor(audio.currentTime);
            const duration = Math.floor(audio.duration);
        }, false);
Respondent: Israt Jahan Simu

Solution #6:

for those who are looking to implement timeupdate in your jquery.

<audio id="myAudio">
    <source src='test.mp3' type="audio/mp3" />
</audio>

$("audio#myAudio").get(0).addEventListener("timeupdate",function(){
        // do your stuff here
    });
Respondent: yourkishore

Solution #7:

On TypeScript:

formatTime(seconds: number): string {

    let minutes: any = Math.floor(seconds / 60);
    let secs: any = Math.floor(seconds % 60);

    if (minutes < 10) {
        minutes = '0' + minutes;
    }

    if (secs < 10) {
        secs = '0' + secs;
    }

    return minutes +  ':' + secs;
}

Remember to replace magic numbers with constants. It’s an example.

Respondent: Ivan Lencina

Solution #8:

  this.player = new Audio(item.url)
  this.player.play()

  this.player.addEventListener('timeupdate', (event) => {
      const currentTime = Math.floor(this.player.currentTime);
      const duration = Math.floor(this.player.duration);
      this.barWidth = (currentTime*100)/duration
  }, false);
Respondent: Monu Mehta

Solution #9:

Not a new answer but a mix of multiple answers. You may try this.

<audio controls src="source_of_audio_file" id="audio" class="audio" ontimeupdate="update_time(this.currentTime, this.duration);" >
  Your browser does not support the audio element.
</audio>


function update_time(current_time, audio_duration){
  $("#currentAudioTime").html(format_time(current_time));
  $("#totalAudioDuration").html(format_time(audio_duration));
}

function format_time(audio_duration){
  sec = Math.floor( audio_duration );
  min = Math.floor( sec / 60 );
  min = min >= 10 ? min : '0' + min;
  sec = Math.floor( sec % 60 );
  sec = sec >= 10 ? sec : '0' + sec;
  return min + ":"+ sec;
}

<div>
  <span id="currentAudioTime"></span> : <span id="totalAudioDuration"></span>
</div>
Respondent: rahim.nagori

Solution #10:

to find the length of a audio file is simple!:

<html>
<head>
</head>
<body>
    <audio controls="" id="audio">
        <source src="audio.mp3">
    </audio>
    <button id="button">
    <p id="p"></p>
        GET LENGTH OF AUDIO
    </button>
<script>
    var MYAUDIO = document.getElementById(audio);
    var MYBUTTON = document.getElementById(button);
    var PARA = document.getElementById(p);
    function getAudioLength() {
        PARA.innerHTML = duration.MYAUDIO
    }
MYBUTTON.addEventListener(click, getAudioLength);
</script>
</body>
</html>
Respondent: Smit Shilpatul

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.