Reputation: 123
I'm making a small asteroid avoiding game and when my lives are over I'm executing the following code:
gameover.play();
while gameover is defined like so:
var gameover = new Audio('gameover.wav');
When I execute the code, it loops the sound and I want to play it just once, how would I do that? Thanks.
Upvotes: 5
Views: 17485
Reputation: 25875
I believe setting the loop
property to false
will accomplish your goal.
const gameSound = new Audio('https://assets.mixkit.co/active_storage/sfx/273/273-preview.mp3');
gameSound.loop = false;
gameSound.play();
const gameSound = new Audio('https://assets.mixkit.co/active_storage/sfx/273/273-preview.mp3');
gameSound.loop = false;
const statusElem = document.getElementById('status');
/** @type {number} */
let startTime;
updateStatus();
function start() {
startTime = Date.now();
gameSound.play();
updateStatus();
}
function updateStatus(){
if (!startTime) {
statusElem.innerText = '(Waiting for interaction)';
} else if (gameSound.ended){
statusElem.innerText = 'Stopped';
} else {
statusElem.innerText = 'Playing (' + ( ( Date.now() - startTime ) / 1000 ) + ')';
window.setTimeout(updateStatus, 50);
}
}
<button onclick="start()">Play Sound</button><br>
<br>
Audio Status: <span id="status">Playing</span>
Tested in:
Upvotes: 7