Henry Oladeji
Henry Oladeji

Reputation: 47

What function can be used to keep playing audio after current one is done

I am trying to play the next song in a playlist/album after the current one has finished playing. I was able to get a song to play but it does not move to the next one after the current one finish playing.

Here is my code:

<button class="controlButton play" title="Play" @click="play" v-if="!isPlaying">
   <img src="storage/icons/play.png" alt="Play">
</button>
<button class="controlButton pause" title="Pause" @click="pause" v-else>
   <img src="storage/icons/pause.png" alt="Pause">
</button>
<script>
import { Link } from "@inertiajs/inertia-vue3";
export default {
    components: {
        Link
    },
    data() {
        return {
            audio: new Audio(),
            currentSong: {},
            myWidth: 0,
            loop:{},
            index: 0,
            songs: [
                {
                    title: 'Song',
                    artist: 'Artis A',
                    src: '/storage/audio/song.mp3',
                    cover: '/storage/images/cover.jpeg',
                },
                {
                    title: 'Song 2',
                    artist: 'Artis B',
                    src: '/storage/audio/song2.mp3',
                    cover: '/storage/images/cover2.jpeg',
                },
 mounted() {
        this.currentSong = this.songs[this.index];
},
methods: {
play(song) {
            if(typeof song.src != 'undefined') {
                this.currentSong = song;
                this.audio.src = this.currentSong.src

            }
            this.audio.play();
            this.isPlaying = true
            this.activeItem = this.currentSong
        },
 pause() {
            this.audio.pause();
            this.isPlaying = false;
        },
}

How can i get the second song to play after the current has finished and also change the button back to play when there is no song left.

Upvotes: 0

Views: 54

Answers (1)

schrej
schrej

Reputation: 450

The Audio object (which is a HTMLAudioElement, which inherits from HTMLMediaElement) exposes a ended event, which you can listen to.

mounted() {
    this.audio.addEventListener('ended', (event) => {
        // go to next song
    })
}

Upvotes: 1

Related Questions