When the audio tag in vue uses refs to get the duration and returns NaN

Recently, when developing a music website, I encountered a situation where I wanted to use the duration of the audio to obtain the total duration of the song, but the result was always NAN, and no result was found after searching for a long time.

Then I observed that NAN appeared only when I clicked too fast. My personal guess may be that the progress bar has not finished loading the song when getting the song. That is to say, we will get the total duration before the song is loaded.

However, I am not good at technology, so I finally thought of a timer and set the time for two seconds, so that I can get the data

 setTimeout(() => {
                console.log(this.$refs.audio.duration)
            }, 2000);

The above methods can also be obtained. I asked my friends today and finally found the correct method.

The reason for getting NAN is that the music has not been loaded. At this time, you need to add it in the audio tag

@canplay="canplay"

In this way we canplay(){

// Get the total duration of the music here

}

Front

<audio   :src="musicdetail.play_url" @canplay="canplaysong" autoplay="true"></audio>

methods inside

canplaysong(){
            let total=parseInt(this.$refs.audio.duration)
                this.musictotaltimemode=total
                let minute=total % 60
                let seconds=(total-minute)/60
                this.musictotaltime=seconds+':'+minute
        },

This way there will be no NAN

Guess you like

Origin blog.csdn.net/qq_43644046/article/details/123532976