Home » Php » javascript – PHP – Android – Play random MP3 files from directory

javascript – PHP – Android – Play random MP3 files from directory

Posted by: admin February 25, 2020 Leave a comment


I am doing a web in PHP, that when entering, it reproduces randomly files in MP3 from a folder, and when finalizing an mp3, it reproduces another one (again of random form).

Everything runs ok in desktop version, but the problem lies in mobile versions. When the smartphone is idle (screen locked), it does not play the next track. I think it must be something related to the foreground and background execution of the Chrome or browser that is being used on Android.

Is there any way from PHP, Javascript or jQuery, to make this not stop? I already tried several options but I can’t solve it.

Then the code used:

$files = glob("mp3/*.mp3");
$random = $files[array_rand($files)];

foreach($files as $file){
$listStr.=($listStr!=='')?", ":"";


<html lang="es">

<audio preload controls autoplay id="bgAudio"  src="<?php echo $random; ?>"></audio>
var playListArray=Array(<?php echo $listStr;?>); //array of files in the playlist
var audioPlayer=document.getElementById('bgAudio'); //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.addEventListener("ended", playNextSound, false); //listens to the end of the playback    
How to&Answers: