Examples
Basic Examples
Single Video Download
use Darkwob\YoutubeMp3Converter\Converter\YouTubeConverter;
use Darkwob\YoutubeMp3Converter\Converter\Options\ConverterOptions;
use Darkwob\YoutubeMp3Converter\Progress\FileProgress;
use Darkwob\YoutubeMp3Converter\Converter\Exceptions\ConverterException;
// Initialize with options
$progress = new FileProgress(__DIR__ . '/progress');
$options = new ConverterOptions();
$options->setAudioFormat('mp3')->setAudioQuality(0); // Highest quality
$converter = new YouTubeConverter(
__DIR__ . '/bin', // FFmpeg and yt-dlp binary path
__DIR__ . '/downloads', // Output directory
__DIR__ . '/temp', // Temporary directory
$progress, // Progress tracker
$options // Converter options
);
// Simple download
try {
$result = $converter->processVideo('https://www.youtube.com/watch?v=VIDEO_ID');
echo "Downloaded: " . $result->getTitle() . "\n";
echo "File: " . $result->getOutputPath() . "\n";
echo "Format: " . $result->getFormat() . "\n";
echo "Size: " . round($result->getSize() / 1024 / 1024, 2) . " MB\n";
echo "Duration: " . round($result->getDuration() / 60, 2) . " minutes\n";
} catch (ConverterException $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Multiple Videos Download
$videos = [
'https://www.youtube.com/watch?v=VIDEO_ID_1',
'https://www.youtube.com/watch?v=VIDEO_ID_2',
'https://www.youtube.com/watch?v=VIDEO_ID_3'
];
$results = [];
foreach ($videos as $video) {
try {
$result = $converter->processVideo($video);
$results[] = $result;
echo "ā Downloaded: " . $result->getTitle() . "\n";
} catch (ConverterException $e) {
echo "ā Failed {$video}: " . $e->getMessage() . "\n";
continue;
}
}
// Summary
echo "\nDownload Summary:\n";
echo "Total files: " . count($results) . "\n";
$totalSize = array_sum(array_map(fn($r) => $r->getSize(), $results));
echo "Total size: " . round($totalSize / 1024 / 1024, 2) . " MB\n";
Get Video Information Only
try {
$info = $converter->getVideoInfo('https://www.youtube.com/watch?v=VIDEO_ID');
echo "Title: " . $info['title'] . "\n";
echo "Duration: " . gmdate('H:i:s', $info['duration']) . "\n";
echo "Upload Date: " . $info['upload_date'] . "\n";
echo "Uploader: " . $info['uploader'] . "\n";
echo "View Count: " . number_format($info['view_count']) . "\n";
echo "Description: " . substr($info['description'], 0, 200) . "...\n";
} catch (ConverterException $e) {
echo "Error getting info: " . $e->getMessage() . "\n";
}
Advanced Examples
High Quality Audio with Metadata
use Darkwob\YoutubeMp3Converter\Converter\Options\ConverterOptions;
$options = new ConverterOptions();
$options
->setAudioFormat('flac') // Lossless audio
->setAudioQuality(0) // Highest quality
->setMetadata([ // Custom metadata
'artist' => 'Artist Name',
'album' => 'Album Name',
'genre' => 'Music',
'date' => '2024'
])
->enableThumbnail(true) // Embed thumbnail
->setOutputTemplate('%(artist)s - %(title)s.%(ext)s'); // Custom filename
$converter = new YouTubeConverter($binPath, $outputPath, $tempPath, $progress, $options);
try {
$result = $converter->processVideo($videoUrl);
echo "High quality FLAC created: " . $result->getOutputPath() . "\n";
} catch (ConverterException $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Different Audio Formats
// MP3 - Most compatible
$mp3Options = new ConverterOptions();
$mp3Options->setAudioFormat('mp3')->setAudioQuality(0);
// AAC - Good quality/size ratio
$aacOptions = new ConverterOptions();
$aacOptions->setAudioFormat('aac')->setAudioQuality(2);
// OPUS - Best compression
$opusOptions = new ConverterOptions();
$opusOptions->setAudioFormat('opus')->setAudioQuality(3);
$formats = [
'mp3' => $mp3Options,
'aac' => $aacOptions,
'opus' => $opusOptions
];
foreach ($formats as $format => $options) {
$converter = new YouTubeConverter($binPath, $outputPath, $tempPath, $progress, $options);
try {
$result = $converter->processVideo($videoUrl);
echo "Created {$format}: " . $result->getOutputPath() . "\n";
} catch (ConverterException $e) {
echo "Failed {$format}: " . $e->getMessage() . "\n";
}
}
Windows Path Handling
use Darkwob\YoutubeMp3Converter\Converter\Util\DirectoryManager;
use Darkwob\YoutubeMp3Converter\Converter\Util\PlatformDetector;
// Windows path normalization
$windowsPath = "C:\\Users\\Username\\Music\\Downloads";
$normalizedPath = DirectoryManager::normalizeWindowsPath($windowsPath);
echo "Normalized path: {$normalizedPath}\n";
// Validate Windows path
$isValid = DirectoryManager::validateWindowsPath($windowsPath);
if ($isValid) {
echo "Path is valid for Windows\n";
} else {
echo "Path contains invalid characters or exceeds length limits\n";
}
// Platform-specific binary detection
$isWindows = PlatformDetector::isWindows();
echo "Running on Windows: " . ($isWindows ? "Yes" : "No") . "\n";
// Get platform-specific binary path
try {
$ytdlpPath = PlatformDetector::getExecutablePath('yt-dlp');
echo "yt-dlp path: {$ytdlpPath}\n"; // Will include .exe on Windows
} catch (BinaryNotFoundException $e) {
echo "Binary not found: " . $e->getMessage() . "\n";
}
// Create converter with Windows compatibility
$converter = new YouTubeConverter(
'C:\\Users\\Username\\Music\\Downloads', // Windows path (automatically normalized)
'C:\\Users\\Username\\AppData\\Local\\Temp', // Windows temp path
new FileProgress('C:\\Users\\Username\\AppData\\Local\\progress'),
$options
);
Using Proxy and Rate Limiting
$options = new ConverterOptions();
$options
->setProxy('socks5://127.0.0.1:1080') // Use SOCKS5 proxy
->setRateLimit(500); // Limit to 500 KB/s
$converter = new YouTubeConverter($binPath, $outputPath, $tempPath, $progress, $options);
try {
$result = $converter->processVideo($videoUrl);
echo "Downloaded via proxy: " . $result->getTitle() . "\n";
} catch (ConverterException $e) {
echo "Proxy error: " . $e->getMessage() . "\n";
}
Date Filtering and Size Limits
$options = new ConverterOptions();
$options
->setDateAfter('20240101') // Only videos after Jan 1, 2024
->setDateBefore('20241231') // Only videos before Dec 31, 2024
->setFileSizeLimit('100M'); // Maximum 100MB files
$converter = new YouTubeConverter($binPath, $outputPath, $tempPath, $progress, $options);
try {
$result = $converter->processVideo($videoUrl);
echo "Downloaded (with filters): " . $result->getTitle() . "\n";
} catch (ConverterException $e) {
echo "Filtered out or error: " . $e->getMessage() . "\n";
}
Progress Tracking Examples
Custom Progress Handler
use Darkwob\YoutubeMp3Converter\Progress\FileProgress;
class CustomProgress extends FileProgress
{
public function update(string $id, string $status, float $progress, string $message): void
{
// Call parent to save to file
parent::update($id, $status, $progress, $message);
// Custom progress display
$progressBar = str_repeat('ā', (int)($progress / 5)) . str_repeat('ā', 20 - (int)($progress / 5));
echo "\r[{$progressBar}] " . round($progress, 1) . "% - {$message}";
if ($status === 'completed') {
echo "\nā Conversion completed!\n";
} elseif ($status === 'error') {
echo "\nā Conversion failed!\n";
}
}
}
$progress = new CustomProgress(__DIR__ . '/progress');
$converter = new YouTubeConverter($binPath, $outputPath, $tempPath, $progress, $options);
Redis Progress Tracking
use Darkwob\YoutubeMp3Converter\Progress\RedisProgress;
// Using Redis extension
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('your-password'); // If password is set
$progress = new RedisProgress($redis, 'converter:', 3600); // 1 hour TTL
$converter = new YouTubeConverter($binPath, $outputPath, $tempPath, $progress, $options);
try {
$result = $converter->processVideo($videoUrl);
echo "Downloaded: " . $result->getTitle() . "\n";
} catch (ConverterException $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Monitoring Progress in Real-time
// Start conversion in background
$pid = pcntl_fork();
if ($pid == 0) {
// Child process - do conversion
try {
$result = $converter->processVideo($videoUrl);
exit(0);
} catch (ConverterException $e) {
exit(1);
}
} else {
// Parent process - monitor progress
$videoId = uniqid('video_', true);
while (true) {
$progressData = $progress->get($videoId);
if ($progressData) {
echo "\rProgress: {$progressData['progress']}% - {$progressData['message']}";
if ($progressData['status'] === 'completed') {
echo "\nConversion completed!\n";
break;
} elseif ($progressData['status'] === 'error') {
echo "\nConversion failed!\n";
break;
}
}
sleep(1);
}
pcntl_wait($status);
}
Remote Converter Examples
Basic Remote Conversion
use Darkwob\YoutubeMp3Converter\Converter\Remote\RemoteConverter;
use Darkwob\YoutubeMp3Converter\Progress\FileProgress;
$progress = new FileProgress(__DIR__ . '/progress');
$remoteConverter = new RemoteConverter(
'https://your-converter-server.com', // Server URL
'your-auth-token', // Authentication token
$progress, // Progress tracker
['format' => 'mp3', 'quality' => 0], // Options
3600, // Timeout (1 hour)
10 // Connection timeout
);
try {
$result = $remoteConverter->processVideo($videoUrl);
echo "Remote conversion completed: " . $result->getTitle() . "\n";
echo "File downloaded to: " . $result->getOutputPath() . "\n";
} catch (ConverterException $e) {
echo "Remote conversion error: " . $e->getMessage() . "\n";
}
Error Handling Examples
Comprehensive Error Handling
try {
$result = $converter->processVideo($videoUrl);
echo "Success: " . $result->getTitle() . "\n";
} catch (ConverterException $e) {
$message = $e->getMessage();
// Check specific error types
if (str_contains($message, 'Invalid URL')) {
echo "Please check the YouTube URL format.\n";
} elseif (str_contains($message, 'Download failed')) {
echo "Could not download video. Check your internet connection.\n";
} elseif (str_contains($message, 'Conversion failed')) {
echo "FFmpeg conversion failed. Check FFmpeg installation.\n";
} elseif (str_contains($message, 'Missing dependency')) {
echo "Required software not found. Install FFmpeg and yt-dlp.\n";
} elseif (str_contains($message, 'Network error')) {
echo "Network connection issue. Try again later.\n";
} else {
echo "Unexpected error: " . $message . "\n";
}
// Log error for debugging
error_log("Converter error: " . $message);
}
Retry Logic
function convertWithRetry($converter, $url, $maxRetries = 3) {
$attempt = 0;
while ($attempt < $maxRetries) {
try {
return $converter->processVideo($url);
} catch (ConverterException $e) {
$attempt++;
if ($attempt >= $maxRetries) {
throw $e; // Final attempt failed
}
echo "Attempt {$attempt} failed: " . $e->getMessage() . "\n";
echo "Retrying in 5 seconds...\n";
sleep(5);
}
}
}
try {
$result = convertWithRetry($converter, $videoUrl);
echo "Success after retry: " . $result->getTitle() . "\n";
} catch (ConverterException $e) {
echo "All retry attempts failed: " . $e->getMessage() . "\n";
}