Originally published on: 2/20/2006 5:58:36 AM
It's been livable (because if you consider anything with MP3's to *not* be livable, your priorities are out of whack), but irritating for a while.
So, last night, I was looking for something to occupy my mind for 20 minutes or so and I figured I'd check this one off of my list. I did a quick lookup of the m3u file format (MP3 playlists if you didn't know) and saw that it's pretty simple.
There's a single line header:
#EXTM3U
followed by a pair of lines for each track in the playlist:
#EXTINF:82,You Are (The Government)
01 - You Are (The Government).mp3
The "82" is the length of the track in seconds, followed by the title of the song. The second line is just the mp3 filename itself (includes a path if you aren't ever going to move the files). I left it relative in my script because it looks in the current directory first. If you were putting your m3u files in a single place, they'd need better paths to where the music is directly.
Anyway, with that bit of information, I went and grabbed a PHP library for reading ID3 tags and set to work. I created a "playlist.php" file in the root directory of the getid3 library.
In that file, I created a single function that takes a directory path and creates a m3u of the mp3's in that directoy and drops it *into* that directory. At the moment, I'm just changing the directory variable and running it manually. However, I may put this function into a recursive script that digs through directories and checks for mp3's. If it finds an mp3 in a directory, it would create an m3u file there as well. That way, I could just point it at the top of the music tree and let it dig through.
But, that's another exercise. Here's the code for playlist.php.
< ?php
require_once('getid3/getid3.php');
function build_playlist($dir){
$getID3 = new getID3;
$files = scandir($dir);
$m3u = "#EXTM3U\n";
foreach($files as $mp3){
if(($mp3 == ".") || ($mp3 == "..")){
} else {
$fileinfo = $getID3->analyze("$dir\\$mp3");
$id3 = $fileinfo['id3v1'];
$album = $id3['album'];
$artist = $id3['artist'];
$length = round($fileinfo['playtime_seconds']);
$title = $id3['title'];
$filename = $mp3;
$m3u .= "#EXTINF:$length,$title\n$filename\n";
}
} if($album){
$playlistname = "$album.m3u";
} else {
$pathinfo = pathinfo($dir);
$playlistname = $pathinfo['basename'] . ".m3u";
}
$handle = fopen("$dir\\$playlistname", 'w');
fwrite($handle, $m3u);
}
$dir = "X:\Bad Religion\Suffer (1988)";
build_playlist($dir);
?>