Hi folks, so on this weekend I decided taking a new challenge.
I saw this Open-source project made by Edgar Muniz Berlinck, and he challenged a few things was up to solve.
Since I cant hesitate on new challenge I decided to take in.
So basically what I had to do is.
1. When the user opens this game, mp3 sound will start, and you have to run all the songs until the end.
I took a few steps first, decided to create a button so i can debugg the code whenever I want.
After than i created a <audio> </audio>
loading up on the website, because this is where the HTML gets the audio.
Before that i saw that if it was HARDCODE like <audio src="./src..."> </audio>
I could load the page, with that information i started to get the hang of it.
Then i created a let playlist = []
this is a array where I will store the src from the songs I want, but if your thinking the same as me the code will be huge.
but STAY WITH ME FOR A SEC.
then I created a .py script
import os
dir_path = r'C:\Users\Carlos Junior\Documents\GitHub\Forked\bar-figth-game\public\assets\songs'
res = []
for path in os.listdir(dir_path):
if os.path.isfile(os.path.join(dir_path, path)):
res.append("'playlist[] = './public/assets/songs/'"+path)
print(res)
this script is writing my javascript code, so I can just copy and paste it on my .js code, what im doing right here is going on the folder where are the songs and list them one by one until the last one and writing the javascript code, so I dont have that much work to do it by hand.
Yep, i know the code looks huge, but im lazy to type it by hand, and the script its not optimized i had to remove 'and enter my playlist.
But it was fun and learned a bit of python.
Okay now lets get to the real code.
document.getElementById('song').addEventListener("click", myFunction)
function myFunction() {
document.getElementById('song').innerHTML = "You clicked me";
const audio = document.querySelector("audio")
let i = 0;
audio.addEventListener('ended', function () {
i = ++i < playlist.length ? i : 0;
console.log(i)
audio.src = playlist[i];
audio.play();
})
audio.volume= 0.1;
audio.loop = false;
audio.src = playlist[getRandom(i)];
console.log(getRandom());
audio.play();
}
function getRandom() {
return Math.floor(Math.random()*playlist.length);
}
So on this code i have a function to use when i click the button, and i have .querySelector aiming to 'audio', and after i started my counter = i, and then i add eventlistener so when the track is = 'ended' started a loop from 0 until the array length of the playlist.
The console.log are just for tracking on this case, and the the audio.src = playlist[i]
this is where the tracks changes.
audio.src = playlist[getRandom(i)];
this is just for User Experience, its kinda annoying you having the same music whenever i enter the game, so i decided to make a random.
And that's it thank you
Top comments (2)
I liked how you write your progress, do more of this!
Will def do more of this ty!