我想知道如何让时间不断更新。因此,当我按下播放按钮时,秒数从0:00开始自动更新到结束,因为现在它仅更新onclick。我正在尝试使用HTML5音频,并且已经成功地从以下代码行中获取时间作为标签进行更新:
sound.ontimeupdate = function () { document.getElementById('Time').innerHTML = sound.currentTime.toFixed() }
但这不是我所需要的,我想在data()中获取时间属性以更新并显示在标签中,如HTML代码所示。
我尝试添加一个事件侦听器,但没有成功...它被调用,并且每次调用都使用console.log记录,但是时间属性未更新
let sound = null
export default {
data () {
return {
isPlaying: false,
time: 0,
duration: 0
}
},
methods: {
playMusic () {
if (!sound) {
sound = new Audio(require('assets/YES.mp3'))
}
this.isPlaying = true
sound.play()
// sound.addEventListener('timeupdate', function () { this.time = sound.currentTime.toFixed() }) -- did not work
this.time = sound.currentTime.toFixed()
}
HTML:
<label id="Time" @timeupdate>
{ { time } }:{ { duration } }
</label>
答案 0 :(得分:0)
在addEventListener
内,您得到的this
与预期不同。
使用fat arrow
sound.addEventListener('timeupdate', () => this.time = sound.currentTime.toFixed() )
或者,按照旧的方式保存this
let that = this
sound.addEventListener('timeupdate', function () { that.time = sound.currentTime.toFixed() })
答案 1 :(得分:0)
您可以只动态添加一个通用计时器。您可以像这样使用手表来添加/删除手表:
(未经测试的代码)
export default {
data() {
return {
isPlaying: false,
time: 0,
duration: 0,
intervalId: null,
sound: null
};
},
watch: {
isPlaying(isPlaying) {
if (this.intervalId !== null) {
clearInterval(this.intervalId);
}
if (isPlaying) {
this.sound.play();
this.intervalId = setInterval(() => {
this.time = this.sound.currentTime.toFixed();
}, 500);
} else {
this.sound.stop();
}
}
},
methods: {
playMusic() {
if (!this.sound) {
this.sound = new Audio(require("assets/YES.mp3"));
}
this.isPlaying = true;
}
}
};