Very Simple PHP Audio Player (With Playlist)

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!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes Audio Player Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Put your audio files into the audio folder.
  • Launch audio.php in the browser.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

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

audio.php
<!-- (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) {
    printf("<div data-src='%s' class='song'>%s</div>", $s, basename($s));
  }} else { echo "No songs found!"; }
?></div>

Yep, there are only 2 components for this simple example.

  1. The audio player, good old <audio> tag.
  2. The playlist.
    • We will use $songs = glob("audio/*.{mp3,webm,ogg,wav}", GLOB_BRACE) to get the list of songs from the audio folder. Take note, glob will not recursively read into sub-folders.
    • Then, loop through $songs and generate the playlist. Take note of the custom data-src here.

 

 

STEP 2) JAVASCRIPT PLAYLIST INIT

audio.js
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);
    };
 
    // (A5) AUTOPLAY FIRST SONG (OPTIONAL)
    aud.play(0);
  }
};
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 an HTMLCollection of songs contained in <div id="demoList">.
    • The idea is to use aud.now to track the current song playing in aud.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.
  • (A5) Optional, play the first song on the list.

 

 

STEP 3) PLAY SONG

audio.js
// (B) START PLAYING
aud.play : (id) => {
  // (B1) UPDATE CURRENT & PLAY
  aud.now = id;
  aud.player.src = aud.playlist[id].dataset.src;
 
  // (B2) A LITTLE BIT OF COSMETIC
  for (let i=0; i<aud.playlist.length; i++) {
    aud.playlist[i].style.backgroundColor = i==id ? "yellow" : "";
  }
};

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.

 

USEFUL BITS & LINKS

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?

P.S. <audio> cannot be styled nor customized (at the time of writing). But we can build one ourselves, check out the custom audio player link below.

 

 

COMPATIBILITY CHECKS

Works on all modern “Grade A” browsers.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

PHP Audio Player With Playlist (click to enlarge)

 

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!

18 thoughts on “Very Simple PHP Audio Player (With Playlist)”

  1. 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.

    1. 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.

      1. 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;

      2. 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/

      3. Get in line dumbo. I see that you are just another self-entitled piece of sh17 desperate to get your project done for free, and you have forgotten your own position. At least learn how to say “thank you” and ask nicely when you are the one seeking help. Dumb@55.

        It’s fun to watch trolls 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”

  2. Wow very nice script. Question – is it possible to add a random “shuffle” feature useable after playlist is loaded?

    Thanks!

    1. Yes. Add your own aud.shuffle flag. aud.player.onended - if (aud.shuffle) { RANDOM } else { NEXT SONG AS USUAL }.

  3. Awesome script!
    Just a little bug: it cannot play a song with a single quote (‘) in the filename
    Please help! Appreciate!

  4. Nice script, one question: Is it possible to make the songs downloadable. I used a similar script which echoes the songs as links but my player-solution was horrible. Your script finally solves my player-issue but now I am missing a download function. Any ideas or tweaks?

  5. Just for clarification, this is just PHP and JavaScript, not dependent to your Core Boxx – PHP Modular Development Framework, right?

    1. Sometimes, people ask the strangest things on planet Earth… I am sure the framework is not even mentioned in the tutorial.

Leave a Comment

Your email address will not be published.