html5 display audio currentTime

前端 未结 9 912
生来不讨喜
生来不讨喜 2020-11-28 05:29

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 sc

相关标签:
9条回答
  • 2020-11-28 06:22

    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;
    }
    
    0 讨论(0)
  • 2020-11-28 06:24

    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.

    0 讨论(0)
  • 2020-11-28 06:25
      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);
    
    0 讨论(0)
提交回复
热议问题