Daniele
Daniele

Reputation: 33

Vuex getters real time updating audio.currentTime state

I want to have audio player in Vuex store to use its data for output to custom audio player in a Vue components.

In Vuex store there is a state property aplayer that plays music. store.js code:

state: {
  aplayer: new Audio()
},
getters: {
  getCurrentTime: state => state.aplayer.currentTime
}

In the component I want to display aplayer.currentTime the current song. I'm trying to get it by using the getter getPlayer in a computed properties.

components.vue code:

getCurrentTime() {
  return this.$store.getters.getCurrentTime;
}

But when output to the template, the current time freezes to 0. However, when I press "pause", the current time is displayed correctly.

Please help.

Upvotes: 2

Views: 1131

Answers (2)

Decade Moon
Decade Moon

Reputation: 34306

Vue works best when observing plain objects, of which Audio is not. Vue cannot detect when the currentTime property changes.

From the docs:

The object must be plain: native objects such as browser API objects and prototype properties are ignored. A rule of thumb is that data should just be data - it is not recommended to observe objects with their own stateful behavior.

Your best solution would be to generate your own currentTime number property and synchronize its value to audio.currentTime periodically by using setInterval while the audio is playing, and clear the interval when the audio is paused.

Upvotes: 2

mestihudson
mestihudson

Reputation: 21

store.js

state: {
  aplayer: new Audio()
},
getters: {
  getCurrentTime: state => state.aplayer.currentTime
}

Component.vue

<template>
  <div>{{getCurrentTime}}</div>
</template>

<script>
  import { mapGetters } from 'vuex'

  export default {
    computed: {
      ...mapGetters(['getCurrentTime'])
    }
  }
</script>

Upvotes: 0

Related Questions