0

I would like to ask why i cannot play an mp3 file from my local pc both with Howler and Html5, but yet i can play a URL with HTML5. It says that it cannot find my local mp3 file either way (howler or html5). I've tried adding './components/t.mp3' '../components/t.mp3' 'src/components/t.mp3' still can't get it to work. Could it be because of NuxtJs? Tried adding type:"audio/mpeg" (for html5) and also, tried different browsers but the problem still persists.

Error message i GET in the browser console:

GET http://localhost:3000/components/t.mp3 net::ERR_ABORTED 404 (Not Found)

code:

<template>
  <div
    class="test"
  >
    <v-btn
      @click="playSound()"
    />
  </div>
</template>
<script>
require('howler')
export default {
  methods: {
    playSound () {
      const sound = new Audio('/components/t.mp3')
      // const sound = new Howl({   --- it doesn't work either.
      //   src: '/components/t.mp3'
      // })
      sound.play()
    }
  }
}
</script>
<style>
.test{
  margin: auto;
}
</style>

Same happens with YES.mp3 enter image description here

CodeNewbie
  • 173
  • 1
  • 10

1 Answers1

2

You have to add your file in assets directory (where static files are) and then require that file. You can do it too with any other path if you do not want to save in your static files.

Example:

/assets/music/file.mp3

data(){
    return {
        music: require('@/assets/music/file.mp3')
    }
},
methods:{
    playMusic(){
       const sound = new Audio(this.music)
       sound.play()
    }
}

Then you can use in your methods with this.music

If you serve with webpack you will have to serve with file-loader adding this to your rules like is explain in this thread: Serving mp3 files using the webpack file loader

NBlack
  • 306
  • 1
  • 7
  • Won't OP need a loader configured for `.mp3` files? I don't think there's one out-of-the-box – Phil Mar 29 '20 at 21:59
  • Not because Vue not "read" sound file as part of the project, its an asset. Im using in one of my projects like this: window.plugins.NativeAudio.preloadSimple( "click", state.sounds.newOrder ); And then: window.plugins.NativeAudio.play("click"); Without loaders. – NBlack Mar 29 '20 at 23:50
  • But Webpack still needs to know how to bundle the assets. The alternative is to just dump everything in the `public` directory – Phil Mar 30 '20 at 00:24
  • 1
    Ok, thats a good point, webpack serve mp3 using file-loader. I attach a thread of how to add rules to MP3 files. – NBlack Mar 30 '20 at 01:12
  • 1
    tank you! also i had to configure webpack https://nuxtjs.org/faq/webpack-audio-files?fbclid=IwAR0d1JZTXwyKlw7KsSvjmDOZggZ71pRVq_Sh1xD2pP8c9JHN7iqXxD1XTTo – CodeNewbie Mar 30 '20 at 08:41