Loop music

This commit is contained in:
Pierre HUBERT 2020-03-23 18:42:31 +01:00
parent 95b0f2ba19
commit ee16d4cf41
2 changed files with 14 additions and 2 deletions

BIN
assets/game.mp3 Normal file

Binary file not shown.

View File

@ -55,11 +55,13 @@ function randInt(min, max) {
* Play an audio file * Play an audio file
* *
* @param {String} url The URL of the audio file to play * @param {String} url The URL of the audio file to play
* @returns {HTMLAudioElement} Generated audio element
*/ */
function playAudio(url) { function playAudio(url) {
const audio = document.createElement("audio"); const audio = document.createElement("audio");
audio.src = url audio.src = url
audio.play(); audio.play();
return audio;
} }
// Get elements // Get elements
@ -99,6 +101,10 @@ async function startGame(gameID) {
return; return;
} }
// Start audio
const audioEl = playAudio("/assets/game.mp3")
audioEl.loop = true;
// Create & apply the canvas // Create & apply the canvas
const canvas = document.createElement("canvas"); const canvas = document.createElement("canvas");
canvas.width = cell_width * level.dimensions[1]; canvas.width = cell_width * level.dimensions[1];
@ -149,8 +155,10 @@ async function startGame(gameID) {
function step() { function step() {
// Check if a game was destroyed // Check if a game was destroyed
if(!canvas.isConnected) if(!canvas.isConnected) {
audioEl.pause();
return; return;
}
// Move the snake if required // Move the snake if required
if(key) { if(key) {
@ -287,6 +295,7 @@ async function startGame(gameID) {
* Call this function once the user loose the game * Call this function once the user loose the game
*/ */
function gameOver() { function gameOver() {
audioEl.pause();
playAudio("assets/gameOver.mp3"); playAudio("assets/gameOver.mp3");
alert("Game over !!!"); alert("Game over !!!");
location.href = "#"; location.href = "#";
@ -297,8 +306,11 @@ async function startGame(gameID) {
if(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(ev.key)) if(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(ev.key))
key = ev.key; key = ev.key;
if(ev.key == "p") if(ev.key == "p") {
audioEl.pause()
alert("Game paused. Close this dialog to resume"); alert("Game paused. Close this dialog to resume");
audioEl.play()
}
}); });
// Automatically generate new map element if required // Automatically generate new map element if required