'How to play audio file with vue.js
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?
Solution 1:[1]
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();
})();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | norbekoff |