Âm thanh trò chơi

Hãy tăng âm lượng. Khi khối màu đỏ chạm vào vật cản, bạn có nghe tiếng va chạm không?






Cách thêm âm thanh?

Hãy sử dụng thẻ HTML5 <audio> để thêm âm thanh và nhạc vào trò chơi của bạn.

Trong ví dụ dưới đây, chúng ta tạo một đối tượng hàm constructor mới để xử lý đối tượng âm thanh:

thực thể

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

Nếu bạn muốn tạo đối tượng âm thanh mới, hãy sử dụng âm thanh hàm构造函数, khi khối đỏ va chạm với vật cản, phát âm thanh:

thực thể

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

Thử ngay

Nhạc nền

Để thêm nhạc nền vào trò chơi, hãy thêm đối tượng sound mới và bắt đầu phát khi bắt đầu trò chơi:

thực thể

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

Thử ngay