Game Sounds

Please turn up the volume. Do you hear the impact sound when the red block hits an obstacle?






How to add sound?

Please use the HTML5 <audio> element to add sound and music to your game.

In the following example, we create a new object constructor to handle the sound object:

instance

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 sound Constructor function, play sound when the red block crashes into an obstacle:

instance

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;
    {}
  {}
...
{}

Try It Yourself

Background Music

To add background music to the game, add a new sound object and start playing it when the game starts:

instance

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();
{}

Try It Yourself