2013-10-14 28 views
0

我正在嘗試將視頻流式傳輸到iPhone。我的情況與this問題幾乎完全相同,只是更具體。我檢索的視頻來自不同的網站,因此我無法更改視頻的檢索方式。使用cURL處理字節範圍請求

我目前必須發佈一些數據到一個URL,我會得到一個視頻回來(如果所有的數據都是有效的)。我目前只是使用cURL獲取數據,將其回顯出來,並將標頭設置爲video/mp4。這在大多數情況下工作正常,但像其他問題 - 它不適用於iPhone。我查了一下,顯然碰到了。現在

,這將是很好,如果我是簡單地讀取從服務器上的文件,但不幸的是,因爲我有具體的數據發佈到服務器實際檢索視頻,這不是這種情況。

我將如何去處理字節範圍請求與捲曲?

回答

0

我通過簡單地下載來自外部源的視頻(整個事情),該數據打開一個流,然後打印出從字節範圍請求所請求的字節的固定這一點。要做到這一點,我修改了答案this answer,所以它只是打開基於我下載的數據流:

function rangeDownload($file) 
{ 
    $fp = fopen('php://memory', 'r+'); 
    fwrite($fp, $file); 
    rewind($fp); 

    $size = strlen($file); 
    $length = $size; 
    $start = 0; 
    $end = $size - 1; 
    header("Accept-Ranges: 0-$length"); 
    if (isset($_SERVER['HTTP_RANGE'])) 
    { 
     $c_start = $start; 
     $c_end = $end; 
     list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2); 
     if (strpos($range, ',') !== false) 
     {    
      header('HTTP/1.1 416 Requested Range Not Satisfiable'); 
      header("Content-Range: bytes $start-$end/$size"); 
      exit; 
     } 

     if ($range == '-') 
      $c_start = $size - substr($range, 1); 
     else 
     { 

      $range = explode('-', $range); 
      $c_start = $range[0]; 
      $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size; 
     } 
     $c_end = ($c_end > $end) ? $end : $c_end; 
     if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) 
     { 

      header('HTTP/1.1 416 Requested Range Not Satisfiable'); 
      header("Content-Range: bytes $start-$end/$size"); 
      exit; 
     } 
     $start = $c_start; 
     $end = $c_end; 
     $length = $end - $start + 1; 
     fseek($fp, $start); 
     header('HTTP/1.1 206 Partial Content'); 
    } 
    header("Content-Range: bytes $start-$end/$size"); 
    header("Content-Length: $length"); 

    $buffer = 1024 * 8; 
    while (!feof($fp) && ($p = ftell($fp)) <= $end) 
    {  
     if ($p + $buffer > $end) 
      $buffer = $end - $p + 1; 
     set_time_limit(0); 
     echo fread($fp, $buffer); 
     flush(); 
    } 

    fclose($fp); 
} 

此代碼假設傳遞給rangeDownload參數是數據的字符串。這是使用的例子:

// curl initialization here... 
$result = curl_exec($ch); 
rangeDownload($result); 

rangeDownload將處理出呼應的數據,並解析所述HTTP範圍。這種方法是不是最好的,但我發現我的外部主機不支持字節範圍請求,所以我不能做它一個更好的方法(除了可能緩存)。除非您無法控制您是否正在從處理字節範圍請求下載數據的位置,否則我不會使用此方法。

相關問題