Skip to content
This repository was archived by the owner on Jan 13, 2023. It is now read-only.

Latest commit

 

History

History
75 lines (73 loc) · 2.01 KB

File metadata and controls

75 lines (73 loc) · 2.01 KB

< Previous     Next >


Use the <audio> element to add sound and music to your games.
In our examples, we create a new object constructor to handle sound objects:
function sound(src) {
  this.sound = document.createElement("audio");
  this.sound.src = src;
  this.sound.setAttribute("preload", "auto");
  this.sound.setAttribute("controls", "none");
  this.sound.style.display = "none";
  document.body.appendChild(this.sound);
  this.play = function(){
    this.sound.play();
  }
  this.stop = function(){
    this.sound.pause();
  }
}
To create a new sound object use the sound constructor, and when the red square hits an obstacle, play the sound:
var myGamePiece;
var myObstacles = [];
var mySound;

function startGame() { myGamePiece = new component(30, 30, "red", 10, 120); mySound = new sound("bounce.mp3"); myGameArea.start(); }

function updateGameArea() { var x, height, gap, minHeight, maxHeight, minGap, maxGap; for (i = 0; i < myObstacles.length; i += 1) { if (myGamePiece.crashWith(myObstacles[i])) { mySound.play(); myGameArea.stop(); return; } } function sound(src) { this.sound = document.createElement("audio"); this.sound.src = src; this.sound.setAttribute("preload", "auto"); this.sound.setAttribute("controls", "none"); this.sound.style.display = "none"; document.body.appendChild(this.sound); this.play = function(){ this.sound.play(); } this.stop = function(){ this.sound.pause(); } } }

Background Music

To add background music to your game, add a new sound object, and start playing when you start the game:
var myGamePiece;
var myObstacles = [];
var mySound;
var myMusic;
function startGame() {
  myGamePiece = new component(30, 30, "red", 10, 120);
  mySound = new sound("bounce.mp3");
  myMusic = new sound("gametheme.mp3");
  myMusic.play();
  myGameArea.start();
}