1

I'm trying to play an audio file in my vue.js project as such:

import sound from '../../recordings/sound.mp4'
const audio = new Audio(sound) 
audio.play()

This works perfectly well, but import may only appear at the top level - not within a function that would ideally accept any audio file.

Now I tried doing it this way:

const audio = new Audio('../../recordings/sound.mp4') 
audio.play()

But then I get this error:

DOMException: Failed to load because no supported source was found

I found a solution to this strange error in this answer: DOMException: Failed to load because no supported source was found

The solution was to use the import statement - but the issue is the the import statement can only be used at the top level - not within a function.

So how can I dynamically play an audio file with vue.js?

etayluz
  • 15,920
  • 23
  • 106
  • 151
  • The error means the source file cannot be played. Please make sure the file exists and can be played in the browser. – evolutionxbox May 06 '22 at 14:16
  • @evolutionxbox - if you will review the question again you will notice that the file most certainly does exist because I am able to play it using the first code snippet but not with the 2nd code snippet. The two paths in both snippets are identical – etayluz May 06 '22 at 14:17
  • No they're not. One is a local import, the other will be what the browser uses. If the file is not available then it won't play – evolutionxbox May 06 '22 at 14:18
  • @evolutionxbox - I think I understand. How can I make the file available to the browser? It's a vue.js project and the recording is parallel to the vue component as per the path above. – etayluz May 06 '22 at 14:20
  • https://cli.vuejs.org/guide/html-and-static-assets.html serve the audio file as a static asset. Then use that path in `new Audio(...)` – evolutionxbox May 06 '22 at 14:21
  • It's not a good idea to import an audio file, better host your file as a static asset somewhere in your public directory and use that in the browser directly – Lk77 May 06 '22 at 14:26
  • @Lk77 - how to I reference the public directory? I've tried doing `var audio = new Audio("../../public/recordings/sound.mp4");` but this still results in the error `DOMException: Failed to load because no supported source was found`. I have ensured that the file is there. – etayluz May 06 '22 at 14:30
  • 1
    You should do `var audio = new Audio("recordings/sound.mp4");` it should work – Lk77 May 06 '22 at 14:31

1 Answers1

0

You can import your audio file inside a function using Dynamic Imports

(async () => {
  let sound = await import('../../recordings/sound.mp4');
  const audio = new Audio(sound);
  audio.play();
})();
norbekoff
  • 1,719
  • 1
  • 10
  • 21
  • Seems like it is the right answer, but vue keeps telling me 'module not found' when importing the sound file , although the path is correct . – Berni Nov 17 '22 at 10:26