Ask coding questions

← Back to all posts
how do you embed mp3 files into html?
LiamDonohue (294)

so i want to play a song in the background of my website.
how would i do that?

Comments
hotnewtop
mwilki7 (1133)

Found this online and it works okay, just not multiple sounds at once

function sound(src) 
{
    this.sound = document.createElement("audio");
    this.sound.src = src;
    this.sound.setAttribute("preload", "auto");
    this.sound.setAttribute("controls", "none");
    this.sound.style.display = "none";
    document.body.appendChild(this.sound);
    this.play = function(){
        this.sound.play();
    }
    this.stop = function(){
        this.sound.pause();
    }    
}

Usage:

var background_music = new sound("name_of_your_sound.mp3");
background_music.play();