2013-01-12 86 views
3

mp3 파일을 파형 이미지로 변환하는 웹 스크립트를 만들어야하고 I came across this website이 필요합니다.PHP로 mp3 파형 생성하기

PHP 파일 .dll과 .exe 파일을 LAMB에서 내 웹 사이트 (호스트 괴물이 호스팅)에 업로드했습니다.

하지만 웹 사이트에서 MP3 파일을 업로드하려고하면 파형 이미지 대신 흑백 이미지가 생성됩니다.

저는 PHP에 대해 거의 알지 못해서 무엇이 잘못되었는지 정확히 알지 못하지만, 프로그램의 업로드 부분과 관련이 있다고 생각합니다.

아무도 저에게 무엇이 잘못되었고 어떻게 해결할 수 있습니까?

다음은 PHP 코드 (있는 그대로 in this repository on GitHub)입니다.

<?php 

    ini_set("max_execution_time", "30000"); 

    // how much detail we want. Larger number means less detail 
    // (basically, how many bytes/frames to skip processing) 
    // the lower the number means longer processing time 
    define("DETAIL", 5); 

    define("DEFAULT_WIDTH", 500); 
    define("DEFAULT_HEIGHT", 100); 
    define("DEFAULT_FOREGROUND", "#FF0000"); 
    define("DEFAULT_BACKGROUND", "#FFFFFF"); 

    /** 
    * GENERAL FUNCTIONS 
    */ 
    function findValues($byte1, $byte2){ 
    $byte1 = hexdec(bin2hex($byte1));       
    $byte2 = hexdec(bin2hex($byte2));       
    return ($byte1 + ($byte2*256)); 
    } 

    /** 
    * Great function slightly modified as posted by Minux at 
    * http://forums.clantemplates.com/showthread.php?t=133805 
    */ 
    function html2rgb($input) { 
    $input=($input[0]=="#")?substr($input, 1,6):substr($input, 0,6); 
    return array(
    hexdec(substr($input, 0, 2)), 
    hexdec(substr($input, 2, 2)), 
    hexdec(substr($input, 4, 2)) 
    ); 
    } 

    if (isset($_FILES["mp3"])) { 

/** 
* PROCESS THE FILE 
*/ 

// temporary file name 
$tmpname = substr(md5(time()), 0, 10); 

// copy from temp upload directory to current 
copy($_FILES["mp3"]["tmp_name"], "{$tmpname}_o.mp3"); 

    // support for stereo waveform? 
$stereo = isset($_POST["stereo"]) && $_POST["stereo"] == "on" ? true : false; 

    // array of wavs that need to be processed 
$wavs_to_process = array(); 

/** 
* convert mp3 to wav using lame decoder 
* First, resample the original mp3 using as mono (-m m), 16 bit (-b 16), and 8 KHz (--resample 8) 
* Secondly, convert that resampled mp3 into a wav 
* We don't necessarily need high quality audio to produce a waveform, doing this process reduces the WAV 
* to it's simplest form and makes processing significantly faster 
*/ 
if ($stereo) { 
     // scale right channel down (a scale of 0 does not work) 
    exec("lame {$tmpname}_o.mp3 --scale-r 0.1 -m m -S -f -b 16 --resample 8 {$tmpname}.mp3 && lame -S --decode {$tmpname}.mp3 {$tmpname}_l.wav"); 
     // same as above, left channel 
    exec("lame {$tmpname}_o.mp3 --scale-l 0.1 -m m -S -f -b 16 --resample 8 {$tmpname}.mp3 && lame -S --decode {$tmpname}.mp3 {$tmpname}_r.wav"); 
    $wavs_to_process[] = "{$tmpname}_l.wav"; 
    $wavs_to_process[] = "{$tmpname}_r.wav"; 
} else { 
    exec("lame {$tmpname}_o.mp3 -m m -S -f -b 16 --resample 8 {$tmpname}.mp3 && lame -S --decode {$tmpname}.mp3 {$tmpname}.wav"); 
    $wavs_to_process[] = "{$tmpname}.wav"; 
} 

// delete temporary files 
unlink("{$tmpname}_o.mp3"); 
unlink("{$tmpname}.mp3"); 

// get user vars from form 
$width = isset($_POST["width"]) ? (int) $_POST["width"] : DEFAULT_WIDTH; 
$height = isset($_POST["height"]) ? (int) $_POST["height"] : DEFAULT_HEIGHT; 
$foreground = isset($_POST["foreground"]) ? $_POST["foreground"] : DEFAULT_FOREGROUND; 
$background = isset($_POST["background"]) ? $_POST["background"] : DEFAULT_BACKGROUND; 
$draw_flat = isset($_POST["flat"]) && $_POST["flat"] == "on" ? true : false; 

$img = false; 

// generate foreground color 
list($r, $g, $b) = html2rgb($foreground); 

// process each wav individually 
for($wav = 1; $wav <= sizeof($wavs_to_process); $wav++) { 

    $filename = $wavs_to_process[$wav - 1]; 

    /** 
    * Below as posted by "zvoneM" on 
    * http://forums.devshed.com/php-development-5/reading-16-bit-wav-file-318740.html 
    * as findValues() defined above 
    * Translated from Croation to English - July 11, 2011 
    */ 
    $handle = fopen($filename, "r"); 
    // wav file header retrieval 
    $heading[] = fread($handle, 4); 
    $heading[] = bin2hex(fread($handle, 4)); 
    $heading[] = fread($handle, 4); 
    $heading[] = fread($handle, 4); 
    $heading[] = bin2hex(fread($handle, 4)); 
    $heading[] = bin2hex(fread($handle, 2)); 
    $heading[] = bin2hex(fread($handle, 2)); 
    $heading[] = bin2hex(fread($handle, 4)); 
    $heading[] = bin2hex(fread($handle, 4)); 
    $heading[] = bin2hex(fread($handle, 2)); 
    $heading[] = bin2hex(fread($handle, 2)); 
    $heading[] = fread($handle, 4); 
    $heading[] = bin2hex(fread($handle, 4)); 

    // wav bitrate 
    $peek = hexdec(substr($heading[10], 0, 2)); 
    $byte = $peek/8; 

    // checking whether a mono or stereo wav 
    $channel = hexdec(substr($heading[6], 0, 2)); 

    $ratio = ($channel == 2 ? 40 : 80); 

    // start putting together the initial canvas 
    // $data_size = (size_of_file - header_bytes_read)/skipped_bytes + 1 
    $data_size = floor((filesize($filename) - 44)/($ratio + $byte) + 1); 
    $data_point = 0; 

    // now that we have the data_size for a single channel (they both will be the same) 
    // we can initialize our image canvas 
    if (!$img) { 
    // create original image width based on amount of detail 
      // each waveform to be processed with be $height high, but will be condensed 
      // and resized later (if specified) 
    $img = imagecreatetruecolor($data_size/DETAIL, $height * sizeof($wavs_to_process)); 

    // fill background of image 
    if ($background == "") { 
     // transparent background specified 
     imagesavealpha($img, true); 
     $transparentColor = imagecolorallocatealpha($img, 0, 0, 0, 127); 
     imagefill($img, 0, 0, $transparentColor); 
    } else { 
     list($br, $bg, $bb) = html2rgb($background); 
     imagefilledrectangle($img, 0, 0, (int) ($data_size/DETAIL), $height * sizeof($wavs_to_process), imagecolorallocate($img, $br, $bg, $bb)); 
    } 
    } 

    while(!feof($handle) && $data_point < $data_size){ 
    if ($data_point++ % DETAIL == 0) { 
     $bytes = array(); 

     // get number of bytes depending on bitrate 
     for ($i = 0; $i < $byte; $i++) 
     $bytes[$i] = fgetc($handle); 

     switch($byte){ 
     // get value for 8-bit wav 
     case 1: 
      $data = findValues($bytes[0], $bytes[1]); 
      break; 
     // get value for 16-bit wav 
     case 2: 
      if(ord($bytes[1]) & 128) 
      $temp = 0; 
      else 
      $temp = 128; 
      $temp = chr((ord($bytes[1]) & 127) + $temp); 
      $data = floor(findValues($bytes[0], $temp)/256); 
      break; 
     } 

     // skip bytes for memory optimization 
     fseek($handle, $ratio, SEEK_CUR); 

     // draw this data point 
     // relative value based on height of image being generated 
     // data values can range between 0 and 255 
     $v = (int) ($data/255 * $height); 

     // don't print flat values on the canvas if not necessary 
     if (!($v/$height == 0.5 && !$draw_flat)) 
     // draw the line on the image using the $v value and centering it vertically on the canvas 
     imageline(
      $img, 
      // x1 
      (int) ($data_point/DETAIL), 
      // y1: height of the image minus $v as a percentage of the height for the wave amplitude 
      $height * $wav - $v, 
      // x2 
      (int) ($data_point/DETAIL), 
      // y2: same as y1, but from the bottom of the image 
      $height * $wav - ($height - $v), 
      imagecolorallocate($img, $r, $g, $b) 
     );   

    } else { 
     // skip this one due to lack of detail 
     fseek($handle, $ratio + $byte, SEEK_CUR); 
    } 
    } 

    // close and cleanup 
    fclose($handle); 

    // delete the processed wav file 
    unlink($filename); 

} 

header("Content-Type: image/png"); 

// want it resized? 
if ($width) { 
    // resample the image to the proportions defined in the form 
    $rimg = imagecreatetruecolor($width, $height); 
    // save alpha from original image 
    imagesavealpha($rimg, true); 
    imagealphablending($rimg, false); 
    // copy to resized 
    imagecopyresampled($rimg, $img, 0, 0, 0, 0, $width, $height, imagesx($img), imagesy($img)); 
    imagepng($rimg); 
    imagedestroy($rimg); 
} else { 
    imagepng($img); 
} 

imagedestroy($img); 

    } else { 

?> 

    <form method="post" action="<?php print $_SERVER["REQUEST_URI"]; ?>"  enctype="multipart/form-data"> 

    <p>MP3 File:<br /> 
    <input type="file" name="mp3" /></p> 

    <p>Image Width:<br /> 
    <input type="text" name="width" value="<?php print DEFAULT_WIDTH; ?>" /></p> 

    <p>Image Height:<br /> 
    <input type="text" name="height" value="<?php print DEFAULT_HEIGHT; ?>" /></p> 

    <p>Foreground Color: <small>(HEX/HTML color code)</small><br /> 
    <input type="text" name="foreground" value="<?php print DEFAULT_FOREGROUND; ?>" /></p> 

    <p>Background Color: (Leave blank for transparent background) <small>(HEX/HTML color code)</small><br /> 
    <input type="text" name="background" value="<?php print DEFAULT_BACKGROUND; ?>" /></p> 

    <p>Draw flat-line? <input type="checkbox" name="flat" /></p> 

    <p>Stereo waveform? <input type="checkbox" name="stereo" /></p> 

    <p><input type="submit" value="Generate Waveform" /></p> 

    </form> 

<?php 

    }  
+0

hoster가 exec() 함수를 지원합니까? – Stefan

+0

@Stefan 확실하지는 않지만 분명히 http://hostmonsterforums.com/archive/index.php/t-6371.html을 읽으면 그렇게 보이지 않습니다. exec()를 대체 할 수있는 것이 있습니까? Thanx – CosmicRabbitMediaInc

+0

호스트에서이 기능을 사용하지 않도록 설정 한 경우에는별로 도움이되지 않습니다. 외부 프로그램을 사용하지 않고 PHP 전용 솔루션을 찾아야 할 것입니다. – Stefan

답변

0

경우,이 스크립트는 오디오 파일 중 하나를 열 수 없습니다 어떤 이유, 그것은 실패하고 블랙 박스를 생성합니다. 따라서 호스트가 exec()를 차단하지 않고 서버 구성에 따라 경로와 관련된 문제 일 수 있습니다.

  • 가)합니다 (간부에서 '절름발이'실행 파일의 전체 경로를 사용하여 간부에 오디오 파일을
  • 사용을 전체 경로를 호출 (: 당신이 중 하나 또는 모두를 다음 시도 할 수도 있습니다)를 호출하고 다른 스크립트에서이
exec("/usr/local/bin/lame /path/to/{$tmpname}_o.mp3 -m m -S -f -b 16 --resample 8 /path/to/{$tmpname}.mp3 && /usr/local/bin/lame -S --decode /path/to/{$tmpname}.mp3 {$tmpname}.wav"); 
0

난 그냥 그 일을 좋은 라이브러리를 발견했습니다 JustWave Project 모든 위에서 언급 한 는 ... 사실 할 일이다

  1. 서버 측에서 waveimage를 생성하려면 실행 라이브러리가 필요합니다. 이 스크립트는 FFMEG을 사용합니다.
  2. 캐시의 경우이 라이브러리는 SQLite를 사용합니다.
  3. 실제 이미지에 FFMEG가없는 경우 로컬에서 이미지 및 파일 데이터를 생성하고 업로드 할 수 있습니다.
  4. 좋은 간단한 출력, 플레이어 포함, 색상 tweakable.

희망 사항은 동일한 필요를 가진 사람에게 도움이되기를 바랍니다.