I’m trying to create a music player similar to Spotify. I created a button that plays and stops music.
I’m using an array of objects for the songs so that i can later add the ‘skip song’ button and switch to the next object in the array.
When i click on the button it doesn’t play the music and doesn’t change the image to the pause button (||).
The button in the centre is the one I’m talking about:
JAVASCRIPT:
let playlist = [{ //the playlist is an array of dictionaries
"title":"Sunflower",
"mp3id":"sunflower",
},{
"title":"What's Up Danger",
"mp3id":"whatsupdanger",
},{
"title":"Scared Of The Dark",
"mp3id":"scaredofthedark",
},{
"title":"Hide",
"mp3id":"hide",
},{
"title":"Calling",
"mp3id":"calling",
},{
"title":"Annihilate",
"mp3id":"annihilate",
}];
let playlistIndex = 0; //start from the beginning of the array
function playlistPlayer(buttonid) {
let image = document.getElementById(buttonid);
let audio = document.getElementById(playlist[playlistIndex]["mp3id"]);
if (audio.paused)
{
audio.play(); //if paused play
image.src='images/pause-button.png';
}
else
{
audio.pause(); //if playing pause
image.src='images/play-button.png';
}
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('playlist-play').addEventListener('click', function() {
playlistPlayer('playlist-play'); });
}
HTML:
<!-- 3 buttons -->
<img src="images/png-skip-left.png" type="button" id="playlist-skip-left">
<img src="images/play-button.png" type="button" id="playlist-play">
<img src="images/png-skip-right.png" type="button" id="playlist-skip-right">
<!-- playlist songs -->
<audio id="sunflower" src="audio/spiderman/sunflower.mp3"></audio>
<audio id="whatsupdanger" src="audio/spiderman/whatsupdanger.mp3"></audio>
<audio id="scaredofthedark" src="audio/spiderman/scaredofthedark.mp3"></audio>
<audio id="hide" src="audio/spiderman/hide.mp3"></audio>
<audio id="calling" src="audio/spiderman/calling.mp3"></audio>
<audio id="annihilate" src="audio/spiderman/annihilate.mp3"></audio>
New contributor
pietro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2