audioUpdationFunction: function(){ // RE-WRITE THIS AGAIN
mainFunction.currentSong.songAudio.addEventListener("timeupdate", ()=>{
audioSlider.max = mainFunction.currentSong.songDuration
audioSlider.value = mainFunction.currentSong.songAudio.currentTime
console.log(audioSlider.value)
// Audio-End detection
let intAudio = parseInt(audioSlider.value)
if(mainFunction.currentSong.songDuration === intAudio){
mainFunction.count++
}
})
audioSlider.addEventListener("input", ()=>{
mainFunction.currentSong.songAudio.currentTime = audioSlider.value
})
},
was trying to make a spotify clone, and this here is my function to update the audio and keep the tracker or the music-slider in sync with the song. this function is triggered when the user presses play, next or previous as when which means when the audio is starting to play these event listeners help to keep them in sync for also when the next song is played or the previous one.
Everything works fine but when the audio ends the count is incremented 3 times.
This code is written in oop mainly objects and not any class. And excuse me if the code looks shit i’m just a 18 newbie doing all by myself..
Thankyou:)
I tried doing chatgpt it gave the correct code but it doesn’t expand on the cause of the problem. Here is the solution. I can give the whole code for better understanding.
here is the chatgpt answer
audioUpdationFunction: function() {
// Remove any existing listeners to avoid duplicates
mainFunction.currentSong.songAudio.removeEventListener("timeupdate", mainFunction.handleTimeUpdate);
// Define the handler as a named function for proper removal
mainFunction.handleTimeUpdate = () => {
audioSlider.max = mainFunction.currentSong.songDuration;
audioSlider.value = mainFunction.currentSong.songAudio.currentTime;
let intAudio = parseInt(audioSlider.value);
if (mainFunction.currentSong.songDuration === intAudio) {
console.log("Song ended");
mainFunction.count++;
console.log("Count:", mainFunction.count);
if (mainFunction.count >= mainFunction.songQueue.length) {
mainFunction.count = 0; // Loop back to the first song if needed
}
mainFunction.currentSong = mainFunction.songQueue[mainFunction.count];
mainFunction.currentSong.songAudio.play();
mainFunction.audioUpdationFunction(); // Reattach for the new song
}
};
// Attach the cleaned-up listener
mainFunction.currentSong.songAudio.addEventListener("timeupdate", mainFunction.handleTimeUpdate);
// Slider manual input handling
audioSlider.addEventListener("input", () => {
mainFunction.currentSong.songAudio.currentTime = audioSlider.value;
});
}