Any luck getting audio to play from JavaScript code?

Trying to get a sound to play when the spacebar is pressed. Any ideas why this won’t play the audio clip when the spacebar is pressed?

/* When the spacebar is pressed play a sound of lasers firing. */
document.addEventListener('keydown', function(e) {
  if (e.keyCode == 32) {
    var sound = document.createElement('audio');
    sound.src = 'https://upload.wikimedia.org/wikipedia/commons/c/c4/Laser_gun_shot_sound.ogg';
    sound.play();
  }
});

I do have another spacebar function:

/* have red laser beam dot emit and fly away from rocketship when pressing the spacebar */
document.addEventListener('keydown', function(e) {
  if (e.keyCode == 32) {
    var x = rocketship.offsetLeft + rocketship.width / 2;
    var y = rocketship.offsetTop + rocketship.height / 2;
    laser.style.left = x + 'px';
    laser.style.top = y + 'px';
    var x_direction = 1;
    var x_speed = 10;
    var x_max = window.innerWidth - laser.width;
    setInterval(function() {
      x += x_direction * x_speed;
      if (x > x_max) {
        x = x_max;
        x_direction = -1;
      } else if (x < 0) {
        x = 0;
        x_direction = 1;
      }
      laser.style.left = x + 'px';
    }, 20);
  }
});
1 Like

I can get sound to play in JSFiddle. Open AI is more limited using playground.

1 Like