Welcome to a tutorial on how to create a simple PHP audio player. Want to create your own podcast or playlist? Once upon a time, we have to fight with digital dragons and use all sorts of plugins to do that. But today, it is nearly as simple as using an <audio>
tag. Read on for the example!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
PHP AUDIO PLAYER
All right, let us now get into how to create a PHP audio player with a playlist.
STEP 1) THE PHP & HTML
<div id="demo">
<!-- (A) AUDIO TAG -->
<audio id="demoAudio" controls></audio>
<!-- (B) PLAYLIST -->
<div id="demoList"><?php
// (B1) GET ALL SONGS
$songs = glob("audio/*.{mp3,webm,ogg,wav}", GLOB_BRACE);
// (B2) OUTPUT SONGS IN <DIV>
if (is_array($songs)) { foreach ($songs as $k=>$s) {
$name = basename($s);
printf("<div data-src='%s' class='song'>%s</div>", rawurlencode($name), $name);
}} else { echo "No songs found!"; }
?></div>
</div>
Yep, there are only 2 components for this simple example.
- The audio player, good old
<audio>
tag. - The playlist.
- We will use
$songs = glob("audio/*.{mp3,webm,ogg,wav}", GLOB_BRACE)
to get the list of songs from theaudio
folder. Take note,glob
will not recursively read into sub-folders. - Then, loop through
$songs
and generate the playlist. Take note of the customdata-src
here.
- We will use
STEP 2) JAVASCRIPT PLAYLIST INIT
var aud = {
// (A) INITIALIZE PLAYER
player : null, // html <audio> element
playlist : null, // html playlist
now : 0, // current song
init : () => {
// (A1) GET HTML ELEMENTS
aud.player = document.getElementById("demoAudio");
aud.playlist = document.querySelectorAll("#demoList .song");
// (A2) LOOP THROUGH ALL THE SONGS, CLICK TO PLAY
for (let i=0; i<aud.playlist.length; i++) {
aud.playlist[i].onclick = () => aud.play(i);
}
// (A3) AUTO PLAY WHEN SUFFICIENTLY LOADED
aud.player.oncanplay = aud.player.play;
// (A4) AUTOPLAY NEXT SONG IN PLAYLIST WHEN CURRENT SONG ENDS
aud.player.onended = () => {
aud.now++;
if (aud.now>=aud.playlist.length) { aud.now = 0; }
aud.play(aud.now);
};
}
};
window.addEventListener("DOMContentLoaded", aud.init);
Unfortunately, <audio>
does not support playlists at the time of writing. So we will need to build our own, var aud
contains the mechanics of our custom playlist player.
- (A1) Get the HTML elements.
aud.player
refers to<audio id="demoAudio">
.aud.playlist
is anHTMLCollection
of songs contained in<div id="demoList">
.- The idea is to use
aud.now
to track the current song playing inaud.playlist
. For example,aud.now = 0
will indicate the first song,aud.now = 1
indicates the second, and so on.
- (A2) Loop through all the songs, attach “click to play”
onclick = aud.play
. - (A3) Just a bit of precaution here, we wait until the song is sufficiently buffered before playing.
- (A4) When the current song ends, we do a
aud.now++
and play the next song automatically.
STEP 3) PLAY SONG
// (B) START PLAYING
aud.play : id => {
// (B1) UPDATE CURRENT & PLAY
aud.now = id;
aud.player.src = "audio/" + aud.playlist[id].dataset.src;
// (B2) A LITTLE BIT OF COSMETIC
for (let i=0; i<aud.playlist.length; i++) {
if (i==id) { aud.playlist[i].classList.add("now"); }
else { aud.playlist[i].classList.remove("now"); }
}
};
Lastly, we have a function that plays the song itself. Very simply, we set aud.play.src
to the selected data-src
. The end. aud.player.oncanplay
will automatically start playing once sufficiently buffered.
EXTRAS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
CUSTOMIZING THE AUDIO PLAYER?
Take extra note that <audio>
cannot be styled or customized (at the time of writing). But we can build one ourselves, check out the custom audio player link below.
COMPATIBILITY CHECKS
- HTML Audio Element – CanIUse
- Arrow Functions – CanIUse
Works on all modern “Grade A” browsers.
LINKS & REFERENCES
- <audio>: The Embed Audio element – MDN
- Custom Audio Player With Playlist – Code Boxx
- Need to read sub-folders? Check out List Files & Folders In PHP – Code Boxx
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Hello, I’m not sure if my post was deleted due to a non correct question, I asked if will it be possible have the name of the current played song between the player and the playlist, or in top of the playlist. Thank you very much for your work.
Yes – Hire your own web developer to do the changes if unsure. Good luck with your project!
https://code-boxx.com/faq#help “Help on a deeper level”
Thank you very much.
É simplesmente espetacular! Parabéns e muito obrigado por compartilhar seu tempo e conhecimento, além de entregar o código completo. É realmente sensacional.
Hello.
Thank you very much for this code.
Can i ask you pls?
1. how to stop playing in loop whole the playlist. I mean to stop playing after the last file and not start from the beginning again.
2. when I run it in mobile….it is very small…..how can be the size of the player and songs name text changed? (increased)
I wish you all the best friend.
Regards
Miroslav
Slovakia, Europe
1)
if (aud.now==aud.playlist.length) { aud.pause(); } else { aud.play(aud.now); }
2) Playlist – Just set the
font-size
in CSS?3) Audio Player – See “CUSTOMIZING THE AUDIO PLAYER” above.
Keep up the good work! You have some really great information on this website.
Your project doesn’t work in IE-11, and doesn’t work on Android.
Is there any room for improvement. does not load (src = “song_001.mp3”) the source of the file.
See “compatibility checks” above, audio and video will not always load on slow/mobile connections. If you want “improved reliability”, you will have to work out your own streaming, buffering, backward and cross-platform compatibility. Good luck with your project.
I am not an IT specialist.
I was counting on specific help, a fix in the audio.js code.
// (B1) UPDATE AUDIO SRC
aud.now = id;
aud.player.src = aud.playlist [id] .dataset.src;
I consider “Is there any room for improvement” as a general request to upgrade this tutorial. Good luck with your personal project once again.
P.S. Internet Exploder 11 will come to its end of life in Jun 2022, there is no point in adding backward support for it. If you want “improvements” and “specific help” – I will highly recommend you actually pay for professional consultation. You should already know that web development is not “plug and play”. 😉
https://code-boxx.com/faq/#help “Requests for new features and tutorials may be considered, but will not be immediately answered”, “No rigorous follow-ups and free consultations”.
https://code-boxx.com/websites-get-help-programming/
I see you have no ambition and you have forgotten about Android phones
Get in line dumb@55. You are just another clueless self-entitled piece of sh17 desperate to get your project done for free. At least learn how to say “thank you” and ask nicely when you are the one begging for help.
It’s fun to watch trolls pee and set themselves on fire while acting smug, but out of topic. Case closed, there are better things to do than wasting time on a snowflake. 😆
https://code-boxx.com/faq/#badatti
https://code-boxx.com/faq/#help “Irrelevant”