norkunas/youtube-dl-php

php的youtube-dl/yt-dlp包装器

v2.7.0 2024-08-28 08:22 UTC

README

这是一个用于youtube-dlyt-dlp的PHP包装器。

Latest Stable Version Latest Unstable Version Total Downloads CI Status License

安装

第一步是下载youtube-dlyt-dlp

第二步是使用Composer安装包装器

composer require norkunas/youtube-dl-php:dev-master

下载视频

<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use YoutubeDl\Options;
use YoutubeDl\YoutubeDl;

$yt = new YoutubeDl();

$collection = $yt->download(
    Options::create()
        ->downloadPath('/path/to/downloads')
        ->url('https://www.youtube.com/watch?v=oDAw7vW7H0c')
);

foreach ($collection->getVideos() as $video) {
    if ($video->getError() !== null) {
        echo "Error downloading video: {$video->getError()}.";
    } else {
        echo $video->getTitle(); // Will return Phonebloks
        // $video->getFile(); // \SplFileInfo instance of downloaded file
    }
}

仅下载音频(需要ffmpeg或avconv和ffprobe或avprobe)

<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use YoutubeDl\Options;
use YoutubeDl\YoutubeDl;

$yt = new YoutubeDl();
$collection = $yt->download(
    Options::create()
        ->downloadPath('/path/to/downloads')
        ->extractAudio(true)
        ->audioFormat('mp3')
        ->audioQuality('0') // best
        ->output('%(title)s.%(ext)s')
        ->url('https://www.youtube.com/watch?v=oDAw7vW7H0c')
);

foreach ($collection->getVideos() as $video) {
    if ($video->getError() !== null) {
        echo "Error downloading video: {$video->getError()}.";
    } else {
        $video->getFile(); // audio file
    }
}

下载进度

<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use YoutubeDl\YoutubeDl;

$yt = new YoutubeDl();
$yt->onProgress(static function (?string $progressTarget, string $percentage, string $size, string $speed, string $eta, ?string $totalTime): void {
    echo "Download file: $progressTarget; Percentage: $percentage; Size: $size";
    if ($speed) {
        echo "; Speed: $speed";
    }
    if ($eta) {
        echo "; ETA: $eta";
    }
    if ($totalTime !== null) {
        echo "; Downloaded in: $totalTime";
    }
});

自定义进程实例化

<?php

declare(strict_types=1);

namespace App\YoutubeDl;

use Symfony\Component\Process\Process;
use YoutubeDl\Process\ProcessBuilderInterface;

class ProcessBuilder implements ProcessBuilderInterface
{
    public function build(?string $binPath, ?string $pythonPath, array $arguments = []): Process
    {
        $process = new Process([$binPath, $pythonPath, ...$arguments]);
        // Set custom timeout or customize other things..
        $process->setTimeout(60);

        return $process;
    }
}
<?php

declare(strict_types=1);

use App\YoutubeDl\ProcessBuilder;
use YoutubeDl\YoutubeDl;

$processBuilder = new ProcessBuilder();

// Provide your custom process builder as the first argument.
$yt = new YoutubeDl($processBuilder);

有问题?

如果您有任何问题,请发起讨论

许可证

此库在MIT许可证下发布。有关详细信息,请参阅捆绑的LICENSE文件。