-1

I'm trying to get java-script or PHP code to read all mp3 files to my website so they can be played in the browser. At the moment I have to program each file individually and this takes a long time so I'm trying to find a way so that my code reads from a folder with all of my mp3 files within it. This is an example of what i have so far:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
    audio 1
    <audio controls>
        <source src="audio1.mp3" type="audio/mpeg">
    </audio>

    audio 2
    <audio controls>
        <source src="audio2.mp3" type="audio/mpeg">
    </audio>
</body>

Thanks for any help!

Benzaboy
  • 1
  • 1
  • 2
    Already voted this question as Too Broad, but also quickly found a duplicate: https://stackoverflow.com/questions/15774669/list-all-files-in-one-directory-php Which itself links to other duplicates. In general, you should always start with Google. It's *highly unlikely* that you're the first person to ever want to list files from a directory with PHP. – David Mar 03 '19 at 13:19

1 Answers1

0

You need PHP to do that, take a look at http://php.net/manual/en/function.readdir.php

From PHP documentation :

    $handle = opendir('/path/to/files')

    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
        //Do something with $entry
    }


    closedir($handle);

A more easy way to do so is using glob() :

foreach(glob('path/to/file/*.mp3') as $entry)
  //Do something with $entry

It also filters out non mp3 files

Adrien
  • 497
  • 4
  • 9
  • thanks, I used a similar piece of the code you linked and in the echo section i used this: ' ' in the same format as my original post, in the browser it shows the correct number of files and the audio box but the length for each file is 0 seconds, could it be that ' $entry ' is being used wrong, and if so, how would it be fixed? – Benzaboy Mar 03 '19 at 13:52
  • Maybe the path of your files is not the correct one, where is the page located relative to your mp3 files ? – Adrien Mar 03 '19 at 14:01
  • the file that its being listed on is /index.php and the files are in /mp3_files/ – Benzaboy Mar 03 '19 at 14:08
  • when i type $entry in echo, it just displays `$entry` (not the actual name) in the browser with the audio box next to it – Benzaboy Mar 03 '19 at 14:09
  • Ah I see your error, `$entry` is not evaluated in your string because is a simple quoted string, it should be a double quoted string, see http://php.net/manual/en/language.types.string.php. You should write `echo "";` – Adrien Mar 03 '19 at 14:15