How to add a MP3 file to a web page and play music when user is loading it

In this example we show how can you embed and play a mp3 file on a web page ...

Home Programming Examples HTML Examples → How to add a MP3 file to a web page and play music when user is loading it
how to add a mp3 file to a web page and play music when user is loading it


Modern web browsers often have autoplay restrictions for media elements to prevent unwanted playback, so in many of them, like for example the latest versions of Chrome, it's not possible to play directly mp3 files, but I show you below two possible approaches that can work with little user interaction.

The first approach is pure Javascript, we create dynamically an audio element and set its source to be the mp3 file and start playing the file if the visitors moves his mouse on the web page or when he clicks anywhere on it.


var audio = document.createElement("AUDIO")
document.body.appendChild(audio);
audio.src = "test.mp3"
document.body.addEventListener("mousemove", function () {
audio.play()
});


With the second example in the HTML markup, we create an audio element with a ID (my_player) and set the src attribute to the path of your MP3 file. The preload attribute is set to "auto" to preload the audio.


<audio id="my_player" src="test.mp3" preload="auto"></audio>

<script>
document.addEventListener('DOMContentLoaded', function() {
var audio = document.getElementById('my_player');

audio.addEventListener('canplaythrough', function() {
audio.play();
});
});
</script>


In the JavaScript code, we use the DOMContentLoaded event to ensure that the JavaScript is executed after the web page finishes loading. Next, we use getElementById() to get a reference to the audio element. Finally, we add an event listener to the audio element for the canplaythrough event, which fires when the browser determines that it can play the audio without interruption. In the event listener, we call the play() method to start playing the audio.
When the web page loads, the JavaScript code automatically plays the audio file specified in the audio element. Remember to replace test.mp3 with the actual file.



See More HTML ExamplesHire Me For A Project






 
Connect with meLinkedIn ProfileFacebook Profile


2024 © SofiaCoder.com
×

Programming ExamplesPHP ExamplesMySQL ExamplesJavaScript ExamplesHTML ExamplesCSS ExamplesNode.js ExamplesOther Home PageSofia Coder LinkedIn ProfileSofia Coder Facebook Profile