Disclaimer

The views expressed on this blog are my own and do not necessarily reflect the views of my employer.

Monday, November 14, 2016

Play all music files from a local or remote directory via web browser

I blogged about Setting up Raspberry Pi with Apache HTTP server to display files from external hard drive over HTTPS with authentication. The external drive in question has a folder called Music and my objective here is to play all MP3 files from the folder one after another, in a random order. I can click on each file and play them one by one, but that's quite inconvenient. So I decided to use PHP to find all files in the directory and play them using HTML5 Audio tag in a random order. The steps are below (on my Raspberry Pi):

1. $ sudo apt-get update && sudo apt-get upgrade

2. Install PHP: $ sudo apt-get install libapache2-mod-php5 php5 php-pear php5-xcache php5-mysql php5-curl php5-gd

3. Go to DocumentRoot $ cd /var/www/html

4. Create a file for testing $ sudo echo "<?php phpinfo(); ?>" | sudo tee index.php

5. Restart Apache $ sudo service apache2 restart

6. Go to your browser and type x.x.x.x/index.php

If everything works Ok proceed to the next step.

I found it difficult to work with Aliases for this exercise. In my previous note I used

Alias /500all "/media/HD500G"

but now I changed it to

Alias /media/HD500G "/media/HD500G"

(so you can work without Aliases, but I wanted to keep it because I may revert it back).

The next step is to create a music.php file under DocumentRoot that will find the MP3 files from a directory and will play the files. The code is below.

<?php
$files = glob("/media/HD500G/Music/Pink_Floyd/*.mp3");
$random = $files[array_rand($files)];
?>
<html>
<body>
<audio id="myRadio" src="<?php echo $random; ?>" controls autoplay></audio>
<?php
$listStr='';
foreach($files as $file){
$listStr.=($listStr!=='')?", ":"";
$listStr.="'$file'";
}
?>
<script type="text/javascript">
var playListArray=Array(<?php echo $listStr;?>); //array of files in the playlist
var audioPlayer=document.getElementById('myRadio'); //audio player HTML element
//Sets the next audio file to be played
function playNextSound(){
//random index from the playList array
var fileIndex=Math.floor(Math.random()*playListArray.length);
//set the audio source file using the random index
audioPlayer.src=playListArray[fileIndex];
}
audioPlayer.addEventListener("ended", playNextSound, false); //listens to the end of the playback
</script>
</body>
</html>
view raw music.php hosted with ❤ by GitHub
Once you have created the file, change the directory name and go to x.x.x.x/music.php on your web browser.

References:
https://www.stewright.me/2015/08/tutorial-install-apache-php-and-mysql-on-a-raspberry-pi-2/
http://www.webdeveloper.com/forum/showthread.php?352807-PROBLEM-play-all-mp3-files-from-dir-PHP

No comments:

Post a Comment