Skip to content

How to add sound

legosiv edited this page Jul 30, 2022 · 2 revisions

add a sound effect by creating an object inside sounds object.

// sounds
var sounds = {
    eat_sfx: {
        audio: new Audio('audio/apple_bite.ogg'),
        isplaying: false,
    }
}

eat_sfx is a sound effect. it will get played whenever the snake eats a food.

add another sound effect by creating another object within sounds, e.g. lets create burb_sfx

// sounds
var sounds = {
    eat_sfx: {
        audio: new Audio('audio/apple_bite.ogg'),
        isplaying: false,
    },
    burb: {
        audio: new Audio('audio/burp.wav'),
        isplaying: false,
    }
}

to create burb add audio property and isplaying property.

to play burp use the function play_sound(sound_sfx) it will restart the audio whenever the sound event occurs.

here is play_sound(sound_sfx) being used inside function checkFoodSnakeCollision()

function checkFoodSnakeCollision() {
    snake = [x[0], y[0]];
    for (var i = 0; i < food_list.length; i++) {
        food = [food_list[i][0], food_list[i][1]];
        if (intersect(snake, food)) {
            //do thing depending on the food type
            console.log("food eaten:"+food_list[i][3]);
            if (food_list[i][3] == 0) {
                // Difficulty reducing is done in onmessage event
            } else if (food_list[i][3] == 1) {
                snake_size+=4;
            } else {
                snake_size+=1;
            }
            food_list.splice(i, 1);
            send_sever(socket, { "food_eaten": i });//sending the food index to the server
            play_sound(sounds.eat_sfx)
        }
    }
}

One last thing, you also have to create an event listener, which will get executed whenever the audio ends. copy the one I have created for eat_sfx and modify it accordingly. To do this dynamically, create a loop that will will iterate through all the effects inside sounds object and add a event listener to the audio property of each sound. you can do this inside init() or a function that will get executed a startup.

sounds.eat_sfx.audio.addEventListener("ended", function(){
    sounds.eat_sfx.audio.currentTime = 0;
    sounds.eat_sfx.isplaying = false
})
Clone this wiki locally