Playing audio with Vue.js

How can I play audio using Vue.js?

It looks like I can't do the normal way.

  import Vue from 'vue'
  import AppView from './components/App.vue'

  console.log('Play outside of vue')
  var audio = new Audio('file.mp3')
  audio.play()

  new Vue({
    el: '#root',
    mounted () {
       console.log('Will it play here?? lol')
       var audio = new Audio('file.mp3')
       audio.play()
    }, 
    render: h => h(AppView)
  })

      

That being said, Audio is undefined? Do I have to import it somehow? Is there a dedicated VUE package for this? or npm package?

I don't really understand, although Audio was just vanilla javascript?

+5


source to share


3 answers


**** edited ****

Time passed and I started to develop more using VueJ and now I can understand this issue better.

The problem was that the sound is defined outside of the scope of the VueJs component. VueJS encapsulates components in their own context. When we declare it from a new Vue hook, it won't know about the existence of this object.

The correct approach would be as follows:



import Vue from 'vue';
import AppView from './components/App.vue';

new Vue({
  el: '#root',
  mounted () {
   console.log('Will it play here?? lol');
   console.log('Play outside of');
   var audio = new Audio('file://path-to-file/file.mp3'); // path to file
   audio.play();
}, 
render: h => h(AppView)
});

      

Also I should mention that trying to access "file: //" in a browser context will NOT work because the browser is in the sandbox. You have to use <input type="file" />

to get the audio source and then put it in the audio variable after manipulating the file itself.

It's also worth noting that this approach will work much better if you create a global plugin for use in the context of Vue this

. This will make the component reusable and available in every instance of the component you need to access, allowing you to play or pause audio from any component source.

+4


source


Use var audio = new Audio(require('./file.mp3'))

this will create the correct path as in var audio = new Audio('file.mp3')

your path 'file.mp3' has been decoded as a string.



+4


source


try using the path to the audio file associated with the location of your script in your environment

0


source







All Articles