A music player looks simple — play, pause, next — but it teaches you three real skills: working with the HTML audio element, keeping the interface in sync with something that changes on its own, and handling time. Here is a complete version.
The plan
- A list of songs (title, artist, file).
- Play, pause, next, and previous buttons.
- A progress bar that moves while the song plays and jumps when clicked.
- The song title and artist, updated on every track change.
The HTML
<audio id="audio"></audio> <h2 id="title">No song loaded</h2> <p id="artist"></p> <input id="progress" type="range" value="0" min="0" max="100"> <button id="prev">⏮ Prev</button> <button id="play">▶ Play</button> <button id="next">Next ⏭</button> The JavaScript
const songs = [ { title: 'Morning Light', artist: 'A. Sharma', file: 'song1.mp3' }, { title: 'City Rain', artist: 'B. Khan', file: 'song2.mp3' }, { title: 'Slow Sunday', artist: 'C. Verma', file: 'song3.mp3' } ]; let current = 0; const audio = document.getElementById('audio'); function loadSong(index) { current = (index + songs.length) % songs.length; audio.src = songs[current].file; document.getElementById('title').textContent = songs[current].title; document.getElementById('artist').textContent = songs[current].artist; } document.getElementById('play').addEventListener('click', () => { if (audio.paused) { audio.play(); document.getElementById('play').textContent = '⏸ Pause'; } else { audio.pause(); document.getElementById('play').textContent = '▶ Play'; } }); document.getElementById('next').addEventListener('click', () => { loadSong(current + 1); audio.play(); }); document.getElementById('prev').addEventListener('click', () => { loadSong(current - 1); audio.play(); }); audio.addEventListener('timeupdate', () => { if (audio.duration) { document.getElementById('progress').value = (audio.currentTime / audio.duration) * 100; } }); document.getElementById('progress').addEventListener('input', (e) => { audio.currentTime = (e.target.value / 100) * audio.duration; }); audio.addEventListener('ended', () => loadSong(current + 1) || audio.play()); loadSong(0); Three details beginners miss
- The modulo trick —
(index + songs.length) % songs.lengthmakes next and previous wrap around cleanly, including going back from the first song. - The progress bar is two-way.
timeupdatemoves it while playing; theinputevent lets the user scrub. You need both. - Autoplay is blocked. Browsers will not let audio play before the user clicks something. Load the first song, but only play after a click — exactly what this code does.
What to add next
Volume control, shuffle, a playlist that highlights the playing song, and saving the last song in localStorage so it resumes where you left off.