Show the current time of a track using VueJS

Is there a way to have the time continuously update itself without needing to click on anything? When I press play, I want the seconds to automatically start updating from 0:00 until the end of the audio track. Currently, the time only updates when clicked. I am using HTML5 audio and so far I have been able to display the time as it updates with this line of code:

sound.ontimeupdate = function () { document.getElementById('Time').innerHTML = sound.currentTime.toFixed() }

However, this is not exactly what I need. I want the time attribute in data() to be updated and displayed in the label according to my HTML code.

I attempted to add an event listener but it didn't work. The function was called, and each call was logged with console.log, but the time attribute wasn't getting updated.

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>

Answer №1

When working with the addEventListener method, you may notice that the context of this is not what you expected.

To solve this issue, one option is to use a fat arrow function.

sound.addEventListener('timeupdate', () => this.time = sound.currentTime.toFixed() )

Alternatively, you can stick to the traditional method by saving the value of this in another variable.

let that = this
sound.addEventListener('timeupdate', function () { that.time = sound.currentTime.toFixed() })

Answer №2

One way to dynamically add a generic timer is to utilize a watch function for adding and removing it:

(code example - untested)

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;
        }
    }
};

Answer №3

Looking to implement vue3 script setup?

<template>
  <audio :src="file.mp3" id="stream" autoplay></audio>
  <span>{{ currentTime }}</span>
</template>

<script setup>
import { onUpdated } from "vue";
const currentTime = ref();
onUpdated(() => {
  let audio = document.getElementById("stream");
  audio.addEventListener("timeupdate", function () {
    currentTime.value = audio.currentTime.toFixed();
  });
});
</script>

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

Refining the nodes and connections within a directed graph by implementing a filter triggered by clicking a button

I have successfully implemented a force-directed graph. My next step is to incorporate buttons in the main HTML data to enable further filtering. Unfortunately, I haven't been able to make it work yet. I would greatly appreciate any suggestions or gui ...

Learn to leverage JavaScript in Node-RED to dynamically display messages based on selected dropdown options

After reviewing this Node-red flow: https://i.stack.imgur.com/y4aDM.png I am struggling with the implementation in my function. There are 3 options in each dropdown, one for meat type and the other for doneness. Once I select a combination from the drop ...

Trying to add a single value to a specific index in a JavaScript array, but it is mistakenly assigning multiple values at once

Currently tackling a matrix algorithm with an early roadblock. The array at hand is: [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ] The goal is to convert it into this: [ [ 0, 0, 0 ], [ 0, 9, 0 ], [ 0, 0, 0 ] ] My plan was to alter the middle value like so ...

Tips for accessing the initial element of an array, storing it in a state, and sending it to a component

Is there a way to access and store the first object from the response data in a state? I attempted to achieve this by utilizing setData and assigning the first object of the data to it: export default function BuildingsDetail({buildingId}) { const [data ...

Tips for fetching a response after sending an ajax request using XMLHttpRequest

/* The following **frontend** function is executed to transmit a new post (in JSON) to the Node server */ addPost(postData) { const xhr = new XMLHttpRequest(); xhr.open('POST', `${process.env.REACT_APP_BACKEND}/posts`); xhr.setRe ...

Using Angular UI Router to Access $scope Beyond the Scope of the UI View

Looking for a way to access $scope outside the UI view in my todo app. The structure is simple, with three panels as shown in this design For the full code, visit here I need to access the to-do detail on the third panel using $rootScope, which currently ...

Incorporating CASL with the latest version of Angular, version

I'm currently working on implementing CASL into my Angular application, but I'm having trouble understanding how to integrate it. // Login Component ngOnInit() { var jsonBody = {}; jsonBody['email'] = 'peter@klaven'; ...

Can webpack integrate React components from a package and then recompile the package?

I am currently in the process of creating an npm package to standardize my layout components that are based on geist components. Initially, I attempted to use the npm package as a local component, but encountered a webpack loader error when trying to read ...

Can you tell me the locations of the src/js and build/js directories?

Just starting out and seeking guidance. I am currently working with Node v4.2.1 and Gulp 3.9.0 on a Windows 7 machine, following along with a tutorial to familiarize myself with the task runner Gulp. I'm attempting to concatenate tasks but I seem to ...

Showing data in json format using Angular

I have designed a data table that showcases a list of individuals along with their information. However, when I click on the datatable, it keeps opening a chat box displaying the details of the last person clicked, overriding all other chat boxes. 1. Is t ...

Where can I locate information on using the .get method?

Recently, I encountered a code snippet on this site that helped me resolve an issue. The individual who provided the code utilized a .GET method that was unfamiliar to me. Here's a sample snippet: If you'd like to see the complete code, you can ...

In Node.js, the `res.send()` function is called before the actual functionality code is executed

As a newcomer to node js, I am currently working on an app where I query the MySql DB and process the results using node js. One issue I have encountered is that if my initial query returns null data, I then need to perform another query and further proc ...

What is the reason for the Express middleware using parenthesis syntax, whereas custom-made middleware does not?

What is the reason behind Express inbuilt middleware using a parenthesis syntax like app.use(express.json()) while custom-made middleware does not use parentheses like app.use(logger)? It seems to throw an error with parentheses. I'm uncertain if th ...

Unable to successfully transfer parameters from AJAX to PHP

I successfully utilized Jquery UI to update the position of my table. Now, I am trying to pass a parameter from AJAX to PHP in order to update my database with the current table position. However, I encountered an issue where I receive a TypeError: data=nu ...

Adaptive Images with jQuery Mobile Listview

I have been experimenting with the classic listview example featuring thumbnails from the jquery mobile documentation. However, when I upload images of different sizes, they do not display properly due to resolution issues. How can this be resolved? Here ...

Asynchronous JavaScript function within a loop fails to refresh the document object model (DOM) despite

I have been working on a function that utilizes ajax to retrieve instructions from a backend server while the page is loading. The ajax code I've written retrieves the instructions based on the number provided and displays them using the response.setT ...

The global variable remains unchanged after the Ajax request is made

I am attempting to utilize AJAX in JavaScript to retrieve two values, use them for calculations globally, and then display the final result. Below are my code snippets. // My calculation functions will be implemented here var value1 = 0; var v ...

Tips for dynamically populating a mat-table dataSource

While working with backend data streaming, I encountered an issue where trying to push an event to dataSource resulted in an error stating that dataSource is not defined. Can anyone provide guidance on how to dynamically add data to a materialize table? s ...

What are the steps to analyze all attributes of a Vue.js state object using the Chrome Devtools console?

Every time I try to inspect live data on a Vue instance in Chrome, I find myself having to click into the object just to see any data because of how all the values have been converted to getters and setters. This image illustrates my frustration. After cl ...

Guide to customizing the Autocomplete jQuery plugin to mimic Google's result replacement feature

I have implemented the jQuery plugin Autocomplete like Google for two form fields - foo and bar (which is dependent on the value of foo): $(function() { $("#foo").autocomplete({ minLength: 3, limit: 5, source : [{ u ...