sliceruk
sliceruk

Reputation: 127

PHP Scrape Mp3 File

I am embedding some mp3 files on my website. The problem is some of the names are different and my website does not know how to embed - unless I define all the files with the correct names.

For example,

http://example.com/chapter1/book-[some random name].001.mp3

I have set up my website so it embeds like this

http://example.com/chapter1/book.001.mp3

Is there any possible solution that I can use with php so it auto fills the [some random name].

Upvotes: 1

Views: 773

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

You have some options,

  1. Output the path to the file correctly (easiest)

  2. Build and store a registry of the mp3s in a db or flat file and use mod_rewrite to pass the parameters to a loader script. (Example below)

<?php 
/* mod_rewrite  .htaccess in chapters folder
RewriteEngine On
Options -Indexes
RewriteBase /chapter1
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*).mp3$ index.php?loadmp3=$1 [L]
*/
$mp3_dir='./mp3s/';
//Example passed url: http://localhost/chapter1/book.002.mp3
if(isset($_GET['loadmp3'])){
    $real_path = get_mp3_list($_GET['loadmp3']);
    if($real_path != false){
        //Result:  ./mp3s/book-next_random_name.002.mp3
        print_r($real_path);
        //Pass the url to a streamer script
    }else{
        //not found
    }
}
/**
 * Build & cache, search for mp3 from array
 */
function get_mp3_list($search){
    global $mp3_dir;
    if(file_exists($mp3_dir.'mp3s.json')){
        $list = json_decode(file_get_contents($mp3_dir.'mp3s.json'),true);
    }else{
        $mp3s = glob($mp3_dir."*.mp3");
        $list = array();
        foreach($mp3s as $mp3){
            if(preg_match("#(\w+)-(\w+).(\d+).mp3#", $mp3, $match)){
                $list[]=array('location'=>$mp3,
                'type'=>$match[1],
                'name'=>$match[2],
                'episode'=>$match[3]);
            }
            if(!empty($list)){file_put_contents($mp3_dir.'mp3s.json', json_encode($list));}
        }
    }

    $search = explode('.',$search,2);
    foreach($list as $mp3){
        if($mp3['type'] == $search[0] && $mp3['episode'] == $search[1]){
            return $mp3['location'];
        }
    }
    return false;
}
/*
$list Example Array 
(
    [0] => Array
        (
            [location] => ./mp3s/book-next_random_name.002.mp3
            [type] => book
            [name] => next_random_name
            [episode] => 002
        )

    [1] => Array
        (
            [location] => ./mp3s/book-some_random_name.001.mp3
            [type] => book
            [name] => some_random_name
            [episode] => 001
        )

)
*/
?>

Hope it helps

Upvotes: 1

Related Questions