使用youtube-dl将歌曲直接下载到访问者的计算机上



我想把youtube视频转换成mp3,然后直接下载到访问者/用户的电脑上。

使用这样的命令,转换和下载到服务器非常容易:

youtube dl--提取音频--音频格式mp3[视频]

我想知道使用php将mp3文件发送到用户计算机的最快选项是什么。

  1. 将歌曲下载(并将其转换为mp3)到服务器(可访问的文件夹),但将输出文件名设置为youtube中的标识符(https://youtube.com/watch?=IDENTIFIER)。这样,当其他人想要相同的文件时,它就不会两次下载相同的文件。在PHP中,你可以得到类似的结果:

    $link = $_GET['link']; // This is the Youtube link
    $id = str_replace("https://youtube.com/watch?=", ""); // This will remove the youtube link itself
    
  2. 下载后,只需打印出文件的链接即可。

  3. 如果您想节省带宽,请检查是否已经存在具有相同标识符的文件。如果是,那么就给用户现有的一个。

希望这能有所帮助

我正在为我的一个网站做同样的事情,我使用以下功能下载&将视频转换为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;
    }
}

现在,每当用户试图下载文件时,我只需从$link = $_GET['link']获得链接,将其传递给函数,并使用以下代码为文件提供服务:

$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');

我强烈建议使用Nginx的X-Accel-Rerect标头或Apache的X-sendfile来提供文件。

最新更新