Responsive, Random, Auto-Play Audio with Timeline, Caption + Cookie

This demo will load a random song every time the page is refreshed. The song title is displayed in the caption box, a toggle switch stops/starts playback and the draggable marker can be moved along the timeline to fast-forward and rewind (on touch devices, a tap anywhere along the timeline has the same effect). A cookie remembers when sound is manually turned off so that it won't auto-play again on return visits. Stop auto-play altogether by following instructions in the JS.

Works in modern browsers and IE9+

Note: Auto-play is disabled in iOS to preserve mobile data packages.

Please view the source of this page for HTML markup, CSS and JS. The relevant PHP is provided below.

You are listening to: ' Time Is Running Out '

PHP Code

This snippet gets all the mp3s in a folder;

<?php
$files = glob('relative/path/to/audio/*.mp3');
// get all .mp3 files from folder
$fname = $files[array_rand($files)]; // get a random filename
$ftext = ucwords(str_replace('_', ' ', basename($fname, '.mp3'))); // format text for display
?>

Here's how a random mp3 populates the audio player;

<audio id="music" preload="auto">
    <source src="<?php echo $fname; ?>"/>
</audio>

And this is how the nicely formatted filename gets in to the infobox;

<div id="infobox">You are listening to: '<b><?php echo $ftext; ?></b>'</div>

Related

More demos and snippets

Did you find this useful? There are more demos and code snippets this way.