HTML igre

7. Dodavanje zvuka

Kako bi dodali zvuk u igru potrebno je upotrijebiti HTML5 <audio> element za dodavanje zvuka ili glazbe.

Primjer (kada crveni kvadratić udari u prepreku glazba se pokreće)

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

Da bismo u igru ​​dodali pozadinsku glazbu, dodajemo novi zvučni objekt i neka se glazba reproducira kada započnemo igru.

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