Skip to content
← Back to Community
Background music
Profile icon
JacobMcPherson1

How would I add background music to all my pages. Because I can't figure out how

Answered by Baconman321 [earned 5 cycles]
View Answer
Voters
Profile icon
JacobMcPherson1
Comments
hotnewtop
Profile icon
Baconman321

I would recommend using JavaScript's Audio().
Since audio is only loaded once the user interacts with the webpage, add a "click" event listener to the body to make sure the user has interacted with the webpage and then start playing the audio.

let audio = new Audio(); //Source goes here: audio.src = "your_src.mp3" document.body.addEventListener("click",function(){ audio.play(); });

There you have it!

The best way to do this is put it in a separate file called "backgroundAudio.js" and link it into all your html files.

Profile icon
JacobMcPherson1

@Baconman321
Is there any way to have the music loop?

Profile icon
Baconman321

@JacobMcPherson1

audio.loop = true;

Profile icon
JacobMcPherson1

@Baconman321
Ok thanks!

Profile icon
RYANTADIPARTHI

Solution

in html, try using audio.

<audio controls> <source src="AUDIO URL"> </audio>

like that. Put your music file, or URL in there.
IT should work

Profile icon
Aliencomel

@RYANTADIPARTHI
but i cant click the play button