url = $url; if ($output) { $this->progressBar = new ProgressBar($output, 100); $this->output = $output; } } public function running($isRunning = null): bool { if (isset($isRunning)) { $this->running = $isRunning; } return $this->running; } public function downloadVideo(string $path) { $this->path = $path; return $this->download($this->getVideoOptions()); } public function downloadAudio(string $path) { $this->path = $path; return $this->download($thjis->getAudioOptions()); } protected function download(array $options) { $dl = new YoutubeDl($options); $dl->onProgress( function ($progress) { $size = $this->formatBytes($progress['size']); if (!$this->running()) { $this->progressBar->start($size); $this->running(true); } $percentage = $progress['percentage']; $this->progressBar->setProgress($size * round($percentage) / 100); } ); // Set the download path where you want to store downloaded data $dl->setDownloadPath($this->getWorkingPath()); try { $video = $dl->download($this->url); $this->progressBar->finish(); $this->running(false); // $this->getWorkingPath() .'/' . $video->getFilename(), Storage::disk('local')->move( 'tmp/youtube/video/' . $video->getFilename(), 'youtube/video/' . $video->getFilename() ); return $video; // $video->getFile(); // \SplFileInfo instance of downloaded file } catch (NotFoundException $e) { dd($e); // Video not found } catch (PrivateVideoException $e) { dd($e); // Video is private } catch (CopyrightException $e) { dd($e); // The YouTube account associated with this video has been terminated due to multiple third-party notifications of copyright infringement } catch (\Exception $e) { dd($e); // Failed to download } } protected function formatBytes(string $bytes) { $units = [ 'GiB' => 1000, 'MiB' => 1, 'KiB' => 0.0001, 'B' => 1, ]; foreach ($units as $u => $size) { if (Str::contains($bytes, $u)) { return Str::replaceFirst($u, '', $bytes) * $size; } } var_dump("bad");die(); return 0; } protected function getWorkingPath() { return Storage::disk('local')->path('tmp/youtube/' . $this->path); } protected function getStoragePath() { return Storage::disk('local')->path('youtube/' . $this->path); } // For more options go to https://github.com/rg3/youtube-dl#user-content-options protected function getVideoOptions() { return [ 'prefer-free-formats' => true, 'no-overwrites' => true, // 'skip-download' => true ]; } // For more options go to https://github.com/rg3/youtube-dl#user-content-options protected function getAudioOptions() { return [ 'extract-audio' => true, 'audio-format' => 'mp3', 'audio-quality' => 0, // best 'output' => '%(title)s.%(ext)s' ]; } }