How can I get the html5 audio's duration time

前端 未结 8 1516
忘掉有多难
忘掉有多难 2020-12-09 15:10

I have a html5 tag in page, but how can I know its duration time?

相关标签:
8条回答
  • 2020-12-09 15:42

    it's better to use the event like this ...

    ObjectAudio.onprogress  =function(){
        if(this.buffered.length){
        var itimeend = (this.buffered.length>1)? this.buffered.end(this.buffered.length-1):this.buffered.end(0);
        ....
            Your code here.......
        }
    }
    
    0 讨论(0)
  • 2020-12-09 15:44

    I was struggling with loading the duration in a React component so following @AlexioVay's solution, here is an answer if you're using React:

    This assumes you are using a ref for your audio component class which you will need to target the audio elements for your play/pause handler(s).

    <audio /> element:

    <audio ref={audio => { this.audio = audio }} src={this.props.src} preload="auto" />
    

    Then in your componentDidMount():

    componentDidMount() {
    
        const audio = this.audio
    
        audio.onloadedmetadata = () => {
            console.log(audio.duration)
            this.setState({
               duration: this.formatTime(audio.duration.toFixed(0))
            })
        }
    }
    

    And finally the formatTime() function:

    formatTime(seconds) {
        const h = Math.floor(seconds / 3600)
        const m = Math.floor((seconds % 3600) / 60)
        const s = seconds % 60
        return [h, m > 9 ? m : h ? '0' + m : m || '0', s > 9 ? s : '0' + s]
            .filter(a => a)
            .join(':')
    }
    

    With this, the duration in h:mm:ss format will display as soon as the audio src data is loaded. Sweetness.

    0 讨论(0)
提交回复
热议问题