I have an audio file which plays songs. I am currently making a slider that is equal to the songs length and current time. You can't use player.currentTime in the watch component in Vue so how would you go about updating a value in realtime equal to player current time.
I currently have the v-model="player.currentTime"
but that only updates when I pause the songs and not real-time.
This is what I have so far
player: new Audio()
this.player.src = this.songs[this.songIndex].src
this.player.play()
Player:
<input
type="range"
name="timeStamp"
ref="time"
v-model.lazy="this.player.currentTime"
step="0.1"
/>
CodePudding user response:
You have to listen to the timeupdate
event. I made a simple sample code:
Output:
<template>
<div style="border: 1px solid gray; border-radius: 5px; padding: 5px;">
<div>
<button @click="play">Play | Pause</button>
{{ timeLabel }}
</div>
<div>
<input
type="range"
:min="0"
:max="duration"
v-model="currentTime"
@input="updateTime"
>
</div>
</div>
</template>
<script>
export default {
name: 'BaseAudioPlayerTest',
data() {
return {
src: 'Spring-Flowers.mp3',
player: null,
duration: 0,
currentTime: 0,
timeLabel: '00:00:00',
};
},
methods: {
play() {
if (this.player.paused) {
this.player.play();
this.duration = this.player.duration;
} else {
this.player.pause();
}
},
updateTime() {
this.player.currentTime = this.currentTime;
},
timeupdate() {
this.currentTime = this.player.currentTime;
const hr = Math.floor(this.currentTime / 3600);
const min = Math.floor((this.currentTime - (hr * 3600)) / 60);
const sec = Math.floor(this.currentTime - (hr * 3600) - (min * 60));
this.timeLabel = `${hr.toString()
.padStart(2, '0')}:${min.toString()
.padStart(2, '0')}:${sec.toString()
.padStart(2, '0')}`;
},
},
mounted() {
this.player = new Audio(this.src);
this.player.addEventListener('timeupdate', this.timeupdate, false);
},
};
</script>
You can find more info here.