Php同时下载和流式传输视频

时间:2015-05-26 06:51:45

标签: php video download youtube stream

我想制作一个php脚本来从youtube上下载视频并同时播放它,这是我的代码..

ini_set('max_execution_time', 0);
ini_set('memory_limit', '512M');

$vid_id = $_GET['vidId'];

if (!file_exists('../cache_files/youtube/' . $vid_id . '.mp4')) {
    $vid_info = file_get_contents('https://www.youtube.com/get_video_info?video_id=' . $vid_id);
    parse_str($vid_info);
    $Array = explode(',', $url_encoded_fmt_stream_map);
    foreach ($Array as $item) {
        parse_str($item);
        $format = trim(substr($type, 0, strpos($type, ';')));
        if ($format = 'video/mp4' && $quality == 'medium') {
            download($url, $vid_id);
            break;
        } else {
            echo $reason;
        }
    }
} else {
    ob_clean();
    flush();
    readfile('../cache_files/youtube/' . $vid_id . '.mp4');
    exit;
}
function download($infile, $outfile)
{
    $chunksize = 100 * (1024 * 1024);
    $parts     = parse_url($infile);
    $i_handle  = fsockopen($parts['host'], 80, $errstr, $errcode, 5);
    $o_handle  = fopen('../cache_files/youtube/' . $outfile . '.mp4', 'wb');
    if ($i_handle == false || $o_handle == false) {
        return false;
    }
    if (!empty($parts['query'])) {
        $parts['path'] .= '?' . $parts['query'];
    }
    $request = "GET {$parts['path']} HTTP/1.1\r\n";
    $request .= "Host: {$parts['host']}\r\n";
    $request .= "User-Agent: Mozilla/5.0\r\n";
    $request .= "Keep-Alive: 115\r\n";
    $request .= "Connection: keep-alive\r\n\r\n";
    fwrite($i_handle, $request);
    $headers = array();
    while (!feof($i_handle)) {
        $line = fgets($i_handle);
        if ($line == "\r\n")
            break;
        $headers[] = $line;
    }
    $length = 0;
    foreach ($headers as $header) {
        if (stripos($header, 'Content-Length:') === 0) {
            $length = (int) str_replace('Content-Length: ', '', $header);
            break;
        }
    }
    $cnt = 0;

    while (!feof($i_handle)) {
        $buf = '';
        echo $buf = fread($i_handle, $chunksize);
        $bytes = fwrite($o_handle, $buf);
        if ($bytes == false) {
            return false;
        }
        $cnt += $bytes;
        if ($cnt >= $length)
            break;
    }
    fclose($i_handle);
    fclose($o_handle);
    if (file_exists('../cache_files/youtube/' . $outfile . '.mp4')) {
        if (!filesize('../cache_files/youtube/' . $outfile . '.mp4') > 1024) {
             unlink('../cache_files/youtube/' . $outfile . '.mp4');
        }
    }
    return $cnt;
}

我像这样使用它

<video controls autoplay>
<source src='http://127.0.0.1/youtube.video.grabber.php?vidId=BYi7Lc2aclY'>
</video>

“youtube.video.grabber.php”文件现在应该开始将文件下载到我的磁盘并同时将其流式传输到客户端并且它可以工作但是我无法将视频移动到前进或后退所以我需要添加一些标题到这个代码,如部分内容和一些其他标题,这是问题,将标题添加到它停止的代码后,将无法再次工作..所以我想知道如何将这些标题添加到此代码或如果你有一个更好的解决方案,同时下载和流式传输文件,能够将视频向后移动或向前移动我将不胜感激,如果你告诉我如何...感谢和抱歉我的英语不好< / p>

0 个答案:

没有答案