使用curl流式传输远程视频URL

时间:2018-07-29 14:48:45

标签: php curl http-headers streaming

我使用这段代码从带有curl的URL流式传输远程视频,它可以被查找和恢复

    ini_set('max_execution_time', 0);
    $useragent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36";
    $v = $_GET['url'];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 222222);
    curl_setopt($ch, CURLOPT_URL, $v);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $info = curl_exec($ch);
    $size2 = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    header("Content-Type: video/mp4");
    $filesize = $size2;
    $offset = 0;
    $length = $filesize;
    if (isset($_SERVER['HTTP_RANGE'])) {
        $partialContent = "true";
        preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);
        $offset = intval($matches[1]);
        $length = $size2 - $offset - 1;
    } else {
        $partialContent = "false";
    }
    if ($partialContent == "true") {
        header('HTTP/1.1 206 Partial Content');
        header('Accept-Ranges: bytes');
        header('Content-Range: bytes '.$offset.
            '-'.($offset + $length).
            '/'.$filesize);
    } else {
        header('Accept-Ranges: bytes');
    }
    header("Content-length: ".$size2);


    $ch = curl_init();
    if (isset($_SERVER['HTTP_RANGE'])) {
        $partialContent = true;

        preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);
        $offset = intval($matches[1]);
        $length = $filesize - $offset - 1;
        $headers = array(
            'Range: bytes='.$offset.
            '-'.($offset + $length).
            ''
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 222222);
    curl_setopt($ch, CURLOPT_URL, $v);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt($ch, CURLOPT_NOBODY, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_exec($ch);

该代码对于可搜索的代码非常有效,但存在一个问题,即开始播放视频需要花费大约10秒的时间。
    为什么要花那个时间?我可以调整它更快吗?

0 个答案:

没有答案
相关问题