Muntadar Muhammad
Muntadar Muhammad

Reputation: 115

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?

Upvotes: 6

Views: 17964

Answers (5)

Max
Max

Reputation: 91

A modern browser will refuse to play any sound without user interaction. Your code should work fine, if started from a user event, like onclick.

Upvotes: 4

Arthur Kindo
Arthur Kindo

Reputation: 111

If you have done it in this way:

var sound = new Audio('sounds/tom-3.mp3');

sound.play();

This does not work in my case, so I did this:

 var sound = new Audio('sounds\\\tom-3.mp3');

 sound.play();

Upvotes: 1

Jay Rathod
Jay Rathod

Reputation: 51

There's this javascript audio library called HOWLER.JS and its really easy to use. Include this script file:

<script src = "https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.1/howler.js"></script>
  • Add this code snippet to your html:

    var sound = new Howl({
        src: ['../audio/test.mp3'],
        autoplay: true,
        loop: true,
        volume: 0.5,
    });
    
    sound.play();
    

For more info visit: HOWLER.JS DOCS

Upvotes: 2

user8866053
user8866053

Reputation:

Just use the HTML5 audio element with the auto play attribute. As mentioned in the comments, browser support for autoplay is tenuous (for good reason) but it works for me in Firefox.

<audio autoplay loop>
  <source src="http://soundbible.com/grab.php?id=464&type=wav"></source>
</audio>

If you want the user to be able to pause the audio, just add a controls attribute:

<audio autoplay controls loop>
  <source src="http://soundbible.com/grab.php?id=464&type=wav"></source>
</audio>

You can also use JS to have a button somewhere else on the page play/pause as used in another answer.

Upvotes: 1

Happy Machine
Happy Machine

Reputation: 1163

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>

Upvotes: 2

Related Questions