Search code examples
javascripthtmlaudiojavascript-audio-api

Why does audio not play in javascript


I want to add background music to my website. I've tried this JS code:

var sound;
function initialAudio() {
    'use strict';
    sound = new Audio();
    sound.src = '../audio/test.mp3';
    sound.loop = true;
    sound.play();
}
window.addEventListener("load", initialAudio);

I have linked the JS and HTML, but when I open the site, the sound doesn't play. Can you please help me?


Solution

  • You need to use an audio element in your html, this is how to do it.

    <!DOCTYPE html>
    <html>
    <body>
    
    <audio id="audioContainer">
      <source src="myMp3.mp3" type="audio/mpeg">
    </audio>
    
    <p>Click the buttons to play or pause the audio.</p>
    
    <button onclick="playMp3()" type="button">Play Mp3</button>
    <button onclick="pauseMp3()" type="button">Pause Mp3</button> 
    
    <script>
    const audioContainer = document.getElementById("audioContainer"); 
    
    function playMp3() { 
      audioContainer.play(); 
    } 
    
    function pauseMp3() { 
      audioContainer.pause(); 
    } 
    </script>
    
    </body>
    </html>