Jason Smith
Jason Smith

Reputation: 123

Play sound ONLY ONCE

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

Answers (1)

JDB
JDB

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:

  • Chrome 44.0.2403.155 (64-bit)
  • Firefox 40.0.2
  • Safari 8.0.6
  • Vivaldi 1.0.94.2 (for giggles)

Upvotes: 7

Related Questions