Playing sound with no click interaction within JS doesn't work?
Very old subject based on my research and this research states the user must interact via clicking, e.g., in order for the sound to be played via:
var theSound = new Audio(srcString);
theSound.play();
In the game I am currently developing, upon my clicking a <a>
, the sound does play.
But ... my game also has a ball that moves around the inside of the window and if the ball hits any of the window's sides, I want a sound to play.
No clicking is involved, just my moving the ball around via certain keys, e.g., "r" and "l".
So how do I do this within JS with no clicking?
CodePudding user response:
You don't necessarily need a click
event. You just need a trusted event. A keypress
event is good enough for starting audio.
CodePudding user response:
check this example , use canplay event then init your game,then inside the event just call play() method, notice that if you never focus the window the sound will be never reproduce, if you have troubles for init the sound after an trusted event need to be fired, you could use a trick , put a click event on your document;
document.addEventListener("click",()=>{
sound.volume = 0;
sound.play();
sound.pause();
sound.volume = 1;
sound.currentTime = 0;
// here remove your listener to avoid multiple calls
});
<html>
<body>
<div style="width:300px;height:300px;border:1px solid;position:relative;">
<div id="ball" style="width:10px;height:10px;background-color:blue;position:absolute;top:100px;">
</div>
</div>
<script>
let sound= new Audio("https://actions.google.com/sounds/v1/alarms/beep_short.ogg");
sound.oncanplay = function(){
let ball = document.getElementById("ball");
let i = 0;
setInterval(()=>{
i= i 10;
ball.style.left = i "px";
if(i>280){
i=0;
sound.play();
}
},200);
};
</script>
</body>
</html>
CodePudding user response:
You should wait calling play()
until the audio object is ready.
HTMLMediaElement: canplay event - Web APIs | MDN
const audio = new Audio('https://upload.wikimedia.org/wikipedia/commons/6/61/Wellerman.wav');
audio.addEventListener('canplay', e => {
console.log('canplay');
audio.play();
});