Search code examples
phpbuffermp3flash

MP3 Flash Player PHP readfile() buffer


I have a mp3 flash player and it works perfectly even showing the loaded part of the song.

<embed src="player.swf" width="70" height="15" 
FlashVars="song=songs/song.mp3"/>

But now I need to load the song from a .php file, so it would be like this way

<embed src="player.swf" width="70" height="15" FlashVars="song=song.php"/>

and this is my song.php

$filename="songs/song.mp3";
header("Expires: -1");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Content-type: audio/mpeg");
header("Content-Transfer-Encoding: binary");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0");
$len = filesize($filename);
header("Content-Length: $len;\n");
$outname=$archivo;
header("Content-Disposition: application/octet-stream");

readfile($filename); 

It works perfect with play/stop button, but the problem is that this way it doesn't show me the loaded part of the song.


Solution

  • After several hours searching for tips/codes/answers, I found a code from Anindya and edited by Mihai Iorga that finally worked for me, check the question here. The code:

    set_time_limit(0);
    $dirPath = "path_of_the_directory";
    $songCode = $_REQUEST['c'];
    $filePath = $dirPath . "/" . $songCode . ".mp3";
    $strContext=stream_context_create(
        array(
            'http'=>array(
            'method'=>'GET',
            'header'=>"Accept-language: en\r\n"
            )
        )
    );
    $fpOrigin=fopen($filePath, 'rb', false, $strContext);
    header('Content-Disposition: inline; filename="song.mp3"');
    header('Pragma: no-cache');
    header('Content-type: audio/mpeg');
    header('Content-Length: '.filesize($filePath));
    while(!feof($fpOrigin)){
      $buffer=fread($fpOrigin, 4096);
      echo $buffer;
      flush();
    }
    fclose($fpOrigin);
    

    So I just replaced this code in my song.php and now it works perfect!