微信 audio 获取 duration 为 NaN 的解决方法
先加load()
myaudio.load(); myaudio.oncanplay = function () { alert(myaudio.duration); }
load() 方法用于在更改来源或其他设置后对音频/视频元素进行更新
duration 的值可以在 canplay 事件发生之前的 durationchange 阶段中获取。
myaudio.ondurationchange= function () { alert(myaudio.duration); }
如果在Vue中:
<template> <audio id="audioPlay" :src="isPlay" @canplay="playing()" @onended="ended()" v-el:audio></audio> </template> <script> export default { computed: { isPlay() { return this.$store.state.audioSrc; } }, methods: { playing() { console.log('audio paly'); }, ended() { console.log('audio end'); } }, } </script>
也可以试试下面这种方法
var load = (musicSrc) => new Promise(resolve => { let audio = new Audio() audio.src = musicSrc audio.addEventListener('canplay', resolve); })
当音频/视频处于加载过程中时,会依次发生以下事件:
loadstart
durationchange
loadedmetadata
loadeddata
progress
canplay
canplaythrough
ios微信下vue项目组件切换并自动播放音频的解决方案
npm包:audio-loader了解下(最后我在微信中遇到的IOS获取不到duration,就是直接通过audio-loader包解决的。)
var load = require('audio-loader') // load one file load('http://example.net/audio/file.mp3').then(function (buffer) { console.log(buffer) // => <AudioBuffer> })
import load from 'audio-loader' load(this.music).then((function (buffer) { _self.$refs.totalTime.textContent = _self.formatTime(buffer.duration)
}))