view('youtube-converter', [
'_csrfToken' => csrf_token(),
]);
}public function download(Request $request)
{
$validatedData = $request->validate([
'url' => 'required|url',
'format' => 'required|in:mp3,mp4',
'quality' => 'required|in:best,720p,1080p'
]);$videoUrl = $validatedData['url'];
$videoFormat = $validatedData['format'];
$quality = $validatedData['quality'];try {
// Determine video quality options
if ($videoFormat == "mp4") {
if ($quality == "best") {
$videoQuality = "best[ext=mp4]";
} elseif (in_array($quality, ["720p", "1080p"])) {
$videoQuality = "bestvideo[height<=" . substr($quality, 0, -1) . "][ext=mp4]";
} else {
$videoQuality = "best[ext=mp4]";
}
} elseif ($videoFormat == "mp3") {
$videoQuality = "bestaudio[ext=m4a]";
}// Ensure downloads directory exists
$downloadsPath = storage_path('app/downloads');
if (!File::exists($downloadsPath)) {
File::makeDirectory($downloadsPath, 0755, true);
}// Construct yt-dlp command
$outputTemplate = $downloadsPath . '/%(title)s.%(ext)s';
$command = [
'yt-dlp',
'--format', $videoQuality,
'--output', $outputTemplate,
'--no-playlist',
'--quiet',
$videoUrl
];// Execute yt-dlp command
$process = new Process($command);
$process->run();if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}// Find the downloaded file
$files = File::files($downloadsPath);
$downloadedFile = collect($files)->last();// Convert to MP3 if needed
if ($videoFormat == "mp3") {
$mp3Path = pathinfo($downloadedFile, PATHINFO_DIRNAME) . '/' .
pathinfo($downloadedFile, PATHINFO_FILENAME) . '.mp3';
$ffmpegCommand = [
'ffmpeg',
'-i', $downloadedFile,
'-vn',
'-acodec', 'libmp3lame',
'-q:a', '2',
$mp3Path
];$ffmpegProcess = new Process($ffmpegCommand);
$ffmpegProcess->run();$downloadedFile = $mp3Path;
}// Return file for download
return Response::download($downloadedFile);} catch (\Exception $e) {
return response()->json([
'error' => 'Download failed: ' . $e->getMessage()
], 500);
}
}
}
?>YouTube Converter YouTube Converter
YouTube Converter
Scroll to Top