rac0208
rac0208

Reputation: 39

Background Music in Javascript Won't Work

I'm creating a small horror game and I can't seem to figure out how to add background music in javascript.

I looked up how to add it and I found a solution on w3schools, but when I tried it out, it didn't work. I'm trying to play the sound called backgroundMusic which is set to an mp3 file called bgmusic.mp3

var jumpscare;
var backgroundMusic;

music();

function music() {
jumpscare = new sound("jumpscare.mp3");
backgroundMusic = new sound("bgmusic.mp3");
backgroundMusic.play();
}

What I'm hoping to happen is for the music to start playing when I open the application.

Upvotes: 2

Views: 1730

Answers (1)

Quinox
Quinox

Reputation: 583

sound isn't a valid constructor, did you mean Audio ?

As far as I know, you need to integrate a html <audio> tag to be able to play a sound.

According to W3School docs:

<audio id="myAudio">
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

And on the script part :

var x = document.getElementById("myAudio"); 
x.play()
x.pause()

EDIT, this should work too :

const audioObj = new Audio(url);
audioObj.play();

A complete list of methods is avalaible here : https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement#Methods

Upvotes: 2

Related Questions