Search code examples
javascripthtmlhtml5-audio

Sounds realization in js game


I was making a simple game in clear js and I have a question about optimization.

So what I need is to keep the music and sounds separately and I have two variants:

  1. Music is an Audio-object and Sounds are a list of Audio-objects for every sound. In that way I have to change (for example) the volume of every sound if it's needed:
let music_player = new Audio('some src');

let sounds = {
  kick: new Audio('some src'),
  jump: new Audio('some src'),
  run: new Audio('some src')
  //there can be more sounds
};

window.addEventListener('click', function(){
  music_player.play();
  sounds.jump.play();
  sounds.kick.play();
});

  1. Music didn't change but Sounds are the one Audio-object now and if I want to play different sounds i have to change the source of it. It can also be the class of SoundPlayer:
let music_player = new Audio('some src');
let sound_player = new Audio('some src');

//list of sounds with their sources
let sounds = {
  kick:'some src',
  jump:'some src',
  run:'some src'
};

function sound_play(sound){
  sound_player.src = sound;
  sound_player.play();
}

window.addEventListener('click', function(){
  music_player.play();
  sound_play(sounds.jump);
  sound_play(sounds.kick);
});

What is the best way in your opinion?


Solution

  • Your question is not clear .. it's not explained enough ..

    But let's try to help ..


    If you used new Audio("src") then you have an audio in your javascript now ..

    But you must know that you cannot play() it until the user interacts with your dom ..

    So I will suppose that the user interacts with the dom now to explain the next:

    • Use anyAudio.play() to play the audio
    • Use anyAudio.pause() to pause the audio
    • Use anyAudio.paused to check if the audio is paused or not
    • Use anyAudio.currentTime to get or set the current time the audio on
    • Use anyAudio.playbackRate to get and set the speed of the audio default: 1
    • Use anyAudio.volume to get and set the volume of the audio default: 1

    Let's say you want to create a function that gets an audio from a list of sounds and play it with a specific volume :

    let sound_player = new Audio("")
    let sounds = {
        kick:'some src',
        jump:'some src',
        run:'some src'
    }
    function sound_play(sound, volume){
        sound_player.src = sound
        sound_player.volume = volume || 1
        sound_player.play()
    }
    

    now your function is ready , but again, be sure to run it after the user interacts with the dom, because it's not going to work if the user didn't interact with dom.