我需要一种方法来下载&将youtube视频转换为mp3即时。我的意思是没有让用户等到文件在我的服务器上下载然后提供服务
我目前正在使用以下功能将mp3文件下载到我的服务器。它将视频链接作为参数并返回下载的文件位置。它还会检查文件是否已下载,如果是,则返回其位置。
function downloadMP3($videolink){
parse_str( parse_url( $videolink, PHP_URL_QUERY ), $parms );
$id = $parms['v'];
$output = "download/".$id.".mp3";
if (file_exists($output)) {
return $output;
}else {
$descriptorspec = array(
0 => array(
"pipe",
"r"
) , // stdin
1 => array(
"pipe",
"w"
) , // stdout
2 => array(
"pipe",
"w"
) , // stderr
);
$cmd = 'youtube-dl --extract-audio --audio-quality 0 --audio-format mp3 --output download/"'.$id.'.%(ext)s" '.$videolink;
$process = proc_open($cmd, $descriptorspec, $pipes);
$errors = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$ret = proc_close($process);
if ($errors) {
//print($errors);
}
return $output;
}
}
现在每当用户尝试下载文件时,我只需获取该链接并将其传递给该函数并使用以下代码来提供该文件:
$downloadpath = downloadMP3($videolink);
$song_name = "song";
header('X-Accel-Redirect: /' . $downloadpath);
header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
header('Content-length: ' . filesize($_SERVER["DOCUMENT_ROOT"]."/".$downloadpath));
header('Content-Disposition: attachment; filename="'.$song_name.'.mp3"');
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');
我已经在线查看,发现人们将youtube-dl -o - VIDEO_URL
与passthru()
一起使用,它可以下载视频而不是mp3文件。
那么有人知道如何实现这一目标吗?