简体   繁体   中英

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?

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>

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

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.

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();

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.

All of your audio files listed in the JavaScript code MUST be named as HTTPS, not HTTP. And obviously, that means the website(s) you are linking to (including yours) must be secure. That is, you need to have your security certificate, and make sure it is activated. It's a security issue with Chrome. I hope that helps. = -)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM