ITPub博客

首页 > IT职业 > IT职场 > PHP实现m3u8并发下载

PHP实现m3u8并发下载

IT职场 作者:lslzf 时间:2021-09-09 09:43:42 0 删除 编辑

直接上代码

 $value) {        if(file_exists('./tmp/'.$key.'.ts')) {            continue;
        }
        $chan->push('xx');
        go(function() use($key, $value, $chan) { 
            echo "nAdd task:".$key;            while(1) {
                $rs = co_curl($value);                if(strlen($rs) > 0) {
                    file_put_contents('./tmp/'.$key.'.ts', $rs);                    break;
                }
            }            echo "nTask ok:".$key;
            $chan->pop();
        });
    }    //确保所有下载已经完成
    for($i = 0; $i push('over');
    }    //合并文件
    foreach ($matches['0'] as $key => $value) {
        file_put_contents('out.mp4', file_get_contents('./tmp/'.$key.'.ts'), FILE_APPEND);
        unlink('./tmp/'.$key.'.ts');
    }    echo "n 下载完成,转换成功 (out.mp4)";
});function co_curl($url, $cookies = '', $data = array(), $userHeaders = array(), $retJson = 0){    while(1) {
        $urlInfo  = parse_url($url);
        $domain   = $urlInfo['host'];        if($urlInfo['scheme'] == 'https') {
            $port = 443;
            $ssl = true;
        } else {
            $port = isset($urlInfo['port']) ? $urlInfo['port'] : 80;
            $ssl = false;
        }
        $filename = $urlInfo['path'];
        $filename .= isset($urlInfo['query']) ? '?' . $urlInfo['query'] : '';

        $cli     = new SwooleCoroutineHttpClient($domain, $port, $ssl);
        $headers = [            'Host'            => $domain,            "User-Agent"      => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36',            'Accept'          => 'text/html,application/xhtml+xml,application/xml',            'Accept-Encoding' => 'gzip',
        ];        if ($userHeaders) {
            $headers = array_merge($headers, $userHeaders);
            $headers = $userHeaders;
        }        if ($cookies) {
            $headers['Cookie'] = $cookies;
        }
        $cli->setHeaders($headers);
        $cli->set(['timeout' => 60]);        if ($data) {            if($data == 'post') {
                $data = '';
            }
            $cli->post($filename, $data);
        } else {
            $cli->get($filename);
        }

        $body = $cli->body;
        $cli->close();        
        if($cli->statusCode statusCode;
            // echo "n body: ".$body;
            // echo "n retry...";
        } else {            return $body;
        }
    }
}

使用方法

php index.php https://doubanzyv1.tyswmp.com/2018/07/30/LSn7hSBfY0LxpKX2/playlist.m3u8

输出文件路径

当前目录的out.mp4



作者:Dorm_Script
链接:https://www.jianshu.com/p/2b576ada4df5

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1070/viewspace-2811648/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    102
  • 访问量
    875