Search code examples
vue.jsnuxt.jshtml5-audio

Audio loaded event in Vue (Nuxt)


I have a Nuxt-based gsap (greensock) animation, where I'm trying to start that animation only when an audio track that I'm loading is available.

The HTML for the audio:

<audio id="explainer_nar" preload="auto">
  <source src="/audio/explainer-nar.mp3" type="audio/mpeg" />
  <source src="/audio/explainer-nar.ogg" type="audio/ogg" />
</audio>

I have my gsap timeline stored in a method called gsap_anim. In that method I start the audio above using:

const narration = document.getElementById('explainer_nar')
narration.currentTime = 0
narration.play()

Now, in my mounted, I want to wait for audio to be loaded BEFORE I start my animation, because when I just use the following:

mounted() {
  this.gsap_anim()
}

The audio doesn't play (presumably because it hasn't loaded yet).

So, in Vue (and specifically Nuxt), how do I set a listener for the HTML5 audio element, so that I only play the gsap_anim method when it's loaded?


Solution

  • The <audio> element emits a canplay event when the browser has enough data to begin playing, and the canplaythrough event when the full media clip is loaded can be played to its end.

    You can add an event listener for canplay/canplaythrough that performs the GSAP animation:

    const narration = document.getElementById('explainer_nar')
    
    narration.addEventListener('canplay', () => {
      // GSAP animation code here...
    })
    
    narration.currentTime = 0
    narration.play()