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:
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();
});
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?
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:
anyAudio.play()
to play the audioanyAudio.pause()
to pause the audioanyAudio.paused
to check if the audio is paused or notanyAudio.currentTime
to get or set the current time the audio onanyAudio.playbackRate
to get and set the speed of the audio default: 1
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.