Mikael Sauriol Saad
Mikael Sauriol Saad

Reputation: 122

Play sound in javascript

So I've put my sound file in a sub folder of my code directory and whenever I try to play it, it says it can't find it.

Here's my code:

PlaySound = function () {
    var audio = new Audio('~/Content/Sound/Down.mp3');
    audio.loop = false;
    audio.play(); 
}

Anyone know why?

This is the error I get when I inspect:

GET http://localhost:5/~/Content/Sound/Down.mp3 
localhost/:1 Uncaught (in promise) DOMException: Failed to load 
because no supported source was found.

Upvotes: 5

Views: 24050

Answers (5)

Mahdi Bekaran
Mahdi Bekaran

Reputation: 1

const audio = new Audio('/file/ringtone.mp3');

if you use ~ you will get an error, for example:

const audio = new Audio('~/file/ringtone.mp3');

Upvotes: 0

Nicolas Zarate
Nicolas Zarate

Reputation: 1

I think the answer is you can't play an audio before the user interact with the window, you need to do PlaySound function clickable in button or something like that

Upvotes: 0

Luca Kiebel
Luca Kiebel

Reputation: 10096

Put the soundfile in the same directory that your HTML file is in.

after that, this code should not give you any errors:

PlaySound = function () {
    var audio = new Audio('Down.mp3');
    audio.loop = false;
    audio.play(); 
}

Your Broswer has to be able to access the Audio file, so if you visit http://localhost:5/~/Content/Sound/Down.mp3, it should actually open the file

Upvotes: 9

Ahsan Jamal
Ahsan Jamal

Reputation: 256

Try giving the absolute path instead of relative one.

use: ./Content/Sound/Down.mp3

or this: /Content/Sound/Down.mp3

Upvotes: 1

varnit
varnit

Reputation: 1907

why don't you use the html5 audio tag

<audio controls>
  <source src="sample.ogg" type="audio/ogg">
  <source src="sample.mp3" type="audio/mpeg">
</audio>

Upvotes: 0

Related Questions