Is there a way to sustain audio playback even after the current track has finished?

I am facing an issue with my code where I am trying to play the next song in a playlist or album after the current one finishes playing. Although I was able to get a song to play, it does not progress to the next one automatically.

Below is the snippet of 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;
        },
}

I need help on how I can ensure that the second song plays automatically after the current one ends and also change the button back to "play" when there are no more songs left in the playlist.

Answer №1

The Audio element, a descendant of HTMLMediaElement in the DOM, provides access to an ended event that can be monitored.

mounted() {
    this.audio.addEventListener('ended', (event) => {
        // move on to the next track
    })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

hapi-auth-cookie: encounters an issue while trying to read cookies for accessing restricted content

I've implemented hapi-auth-cookie for managing cookies and sessions on my website. Certain parts are restricted and can only be accessed after authentication. When a non-logged-in user tries to access these areas, they are redirected to the login rout ...

retrieve information instantly on AngularJS by utilizing $http or $resource

I designed a plugin for field customization. angular.module('ersProfileForm').directive('ersProfileEditableField', ['$templateCache', '$compile', 'profileFieldService', 'RolesService', ...

Is there a discrepancy in the JSON algorithm?

While using google chrome, I encountered the following scenario: I had an object in javascript that looked like this: var b = { text: 'hello world, you "cool"' }; I then used JSON.stringify to convert it to a string and sent it to the dat ...

Enhancing ag-grid with alternating row group colors following row span

My data structure is shown below: https://i.stack.imgur.com/fy5tn.png The column spanning functionality in ag-grid is working for columns 1 and 2 as expected. However, I am looking to implement alternate row colors based on the values in column 2 (animal ...

Wildcard routes for publicly accessible files

I have a collection of "widgets" with both client and server-side .coffee files (client representing Backbone.js model/view and server corresponding to ExpressJS routes), all organized within the main project directory: my-node-expressjs3-project/ src/ ...

Why won't console.log function execute in this particular situation?

(function( $ ){ $.fn.openlayers = function( mapElementId, options ) { alert(console.log); console.log(options); ... } }); While attempting to enhance the capabilities of a JavaScript library, I encountered an unexpected issue. ...

"An error occurred in Vue: The property or method 'msg' is not defined on the current instance but is being referenced during rendering. Please check your code for any typos or missing declarations

This is the code for my view page <div id="app"> @{{ msg }} @{{ content }} Including a form here <form method="post" enctype="multipart/form-data" v-on:submit.prevent="addPost"> <textarea v-model="content" id="postTe ...

Why does the pound symbol in z-index always show up in Angular?

Having an issue with my code where I set a z-index in the CSS like this: .mat-mini-fab { position: absolute; right: 5px; top: 4px; z-index: 999; box-shadow: none !important; } However, whenever I visit my site, the z-index is not being appl ...

How to handle multiple file uploads and save information in dual tables using Laravel

Currently, I am dealing with a <form> that allows users to upload multiple files. However, my requirement is to store these uploaded files in a separate table within the database. Unfortunately, the files are not being saved into the database for som ...

Is there a way to use HTML and CSS to switch the style of a dynamic decimal number to either Roman numerals or Katakana characters within a specified HTML element, such as a tag, div

I've searched everywhere but only found guides on list styling and counter styling in CSS that didn't work out. So, for example, I have a number inside an HTML tag that is changed dynamically using Vue Watch. I want to display the number in upper ...

Having difficulty passing a function as a parameter from a NextJS component

I have a code snippet like this in a NextJS component: const [currentGPS, setCurrentGPS] = useState({coords:{latitude:0.0,longitude:0.0}}) useEffect(() => { utl.getGPSLocation( (v:{coords: {latitude:number; longitude:n ...

DiscordjsError: The client attempted to use a token that was not accessible

Hey there, I'm currently working on implementing a bot for my server and encountered an issue while attempting to create a member counter for voice channels. After completing the setup, I ran node index.js in the terminal, only to receive an error ind ...

Is it possible to scroll a div on mobile without the need for jQuery plugins?

Upon investigating the initial query, we managed to implement D3js for identifying a scroll event. This allowed us to scroll the div #scroll-content from any location on desktop devices. However, we encountered an issue where this method does not function ...

Guide to making a request in Node.js to Amazon S3 for downloading a specific file

Recently, I encountered an issue while trying to download a file from Amazon S3 using Node.js. Upon receiving the response, I noticed that there were 2 problems with the Buffer data: When I tried sending the buffer from Node.js to the frontend using res ...

Highcharts - Troubleshooting the chart reflow feature

Take a look at the fiddle I created. I encountered an issue with the chart width when toggling the sidebar. After seeking help on Stack Overflow from this post, I was able to solve it. Now, I'm facing another bug where adding transitions while togg ...

Creating a toggle label using just CSS: a step-by-step guide

Recently, I was trying to create a toggle label using HTML, CSS, and JavaScript. Here is the code snippet that I experimented with: function genre_itemclick(item){ if(item.classList.contains('light_blue_border_button')) { ...

Accept a set of objects within php controller

How can I successfully send an array of objects to a PHP controller using AngularJS? $http({ method: 'POST', url: "payment/pagamento", data: $.param(vm.listProdsCar), headers: {'Content-Type': 'appl ...

Is there a method to verify the presence of a message event listener already?

Is there a method to determine if a message event listener is already in place? I am trying to accomplish something similar to this: if(noMessageEventListenerExists) { globalThis.addEventListener('message', async function (data) {}) } I have ...

I need to link the click function to the li components within the xpages autocomplete feature

I've successfully implemented Tim Tripcony's advanced type-ahead solution and it's working well. However, I'd like to customize it a bit by redirecting the user to the selected document instead of filling the editbox with the selected d ...

Eliminate Quotation Marks and Commas in String Data Using React

I created a code snippet to input data into a table and added a button function for downloading the entire table. However, when I open the downloaded file using notes or a text editor, it shows multiple double quotes and commas that I need to eliminate. He ...