Basic Usage - darkwob/youtube-mp3-converter GitHub Wiki
Basic Usage
This guide covers the fundamental usage patterns of the YouTube MP3 Converter library.
Prerequisites
Before starting, ensure you have:
- ✅ Installed the library via Composer
- ✅ Placed required binaries in
bin/directory (yt-dlpandffmpeg) - ✅ Created necessary directories (
downloads,temp,progress)
If you haven't completed these steps, see Getting Started.
Simple Video Conversion
Basic Example
<?php
require_once 'vendor/autoload.php';
use Darkwob\YoutubeMp3Converter\Converter\YouTubeConverter;
use Darkwob\YoutubeMp3Converter\Progress\FileProgress;
// Create converter (binaries auto-detected with Windows support)
$converter = new YouTubeConverter(
outputPath: './downloads',
tempPath: './temp',
progress: new FileProgress('./progress')
);
// Convert a YouTube video to MP3
$result = $converter->processVideo('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
// Access conversion results
echo "✓ Conversion completed!\n";
echo "Title: {$result->getTitle()}\n";
echo "File: {$result->getOutputPath()}\n";
echo "Size: " . round($result->getSize() / 1024 / 1024, 2) . " MB\n";
echo "Duration: {$result->getDuration()} seconds\n";
echo "Format: {$result->getFormat()}\n";
echo "Video ID: {$result->getVideoId()}\n";
With Custom Options
<?php
use Darkwob\YoutubeMp3Converter\Converter\YouTubeConverter;
use Darkwob\YoutubeMp3Converter\Converter\Options\ConverterOptions;
use Darkwob\YoutubeMp3Converter\Progress\FileProgress;
// Configure conversion options
$options = new ConverterOptions();
$options->setAudioFormat('mp3')
->setAudioQuality(0); // Quality scale 0-9 (0 = highest)
// Create converter with options
$converter = new YouTubeConverter(
outputPath: './downloads',
tempPath: './temp',
progress: new FileProgress('./progress'),
options: $options
);
// Convert video
$result = $converter->processVideo('https://www.youtube.com/watch?v=VIDEO_ID');
echo "Converted to {$result->getFormat()} format\n";
Progress Tracking
File-Based Progress Tracking
<?php
use Darkweb\YoutubeMp3Converter\Progress\FileProgress;
// Create progress tracker that saves to files
$progress = new FileProgress('./progress');
$converter = new YouTubeConverter(
outputPath: './downloads',
tempPath: './temp',
progress: $progress
);
// Start conversion (progress automatically tracked)
$result = $converter->processVideo('https://www.youtube.com/watch?v=VIDEO_ID');
// Check progress during conversion (in another script)
$progressData = $progress->get($result->getVideoId());
echo "Status: {$progressData['status']}\n";
echo "Progress: {$progressData['percentage']}%\n";
echo "Message: {$progressData['message']}\n";
Custom Progress Tracking
<?php
use Darkweb\YoutubeMp3Converter\Progress\Interfaces\ProgressInterface;
// Create custom progress tracker
class CustomProgress implements ProgressInterface
{
public function update(string $id, string $status, int $percentage, string $message): void
{
echo "[{$id}] {$status}: {$percentage}% - {$message}\n";
}
public function get(string $id): array
{
return [
'status' => 'unknown',
'percentage' => 0,
'message' => 'No data'
];
}
}
$progress = new CustomProgress();
$converter = new YouTubeConverter(
outputPath: './downloads',
tempPath: './temp',
progress: $progress
);
// Progress will be displayed in real-time
$result = $converter->processVideo('https://www.youtube.com/watch?v=VIDEO_ID');
Error Handling
Basic Error Handling
<?php
use Darkwob\YoutubeMp3Converter\Converter\Exceptions\{
ConverterException,
InvalidUrlException,
BinaryNotFoundException,
DirectoryException,
ProcessException,
NetworkException
};
try {
$result = $converter->processVideo('https://www.youtube.com/watch?v=INVALID_ID');
echo "Success: {$result->getTitle()}\n";
} catch (InvalidUrlException $e) {
echo "Invalid URL: " . $e->getMessage() . "\n";
} catch (BinaryNotFoundException $e) {
echo "Missing binary: " . $e->getMessage() . "\n";
} catch (DirectoryException $e) {
echo "Directory error: " . $e->getMessage() . "\n";
} catch (ProcessException $e) {
echo "Process error: " . $e->getMessage() . "\n";
} catch (NetworkException $e) {
echo "Network error: " . $e->getMessage() . "\n";
} catch (ConverterException $e) {
echo "Conversion error: " . $e->getMessage() . "\n";
} catch (\Exception $e) {
echo "Unexpected error: " . $e->getMessage() . "\n";
}
Comprehensive Error Handling
<?php
function convertVideo(string $url): ?array
{
try {
$converter = new YouTubeConverter(
outputPath: './downloads',
tempPath: './temp',
progress: new FileProgress('./progress')
);
$result = $converter->processVideo($url);
return [
'success' => true,
'data' => [
'title' => $result->getTitle(),
'file' => $result->getOutputPath(),
'size' => $result->getSize(),
'duration' => $result->getDuration()
]
];
} catch (ConverterException $e) {
error_log("Converter error: " . $e->getMessage());
return [
'success' => false,
'error' => $e->getMessage(),
'type' => 'converter_error'
];
} catch (\Exception $e) {
error_log("Unexpected error: " . $e->getMessage());
return [
'success' => false,
'error' => 'An unexpected error occurred',
'type' => 'system_error'
];
}
}
// Usage
$result = convertVideo('https://www.youtube.com/watch?v=VIDEO_ID');
if ($result['success']) {
echo "✓ Converted: " . $result['data']['title'] . "\n";
} else {
echo "✗ Error: " . $result['error'] . "\n";
}
Working with ConversionResult
The processVideo() method returns a ConversionResult object with useful information:
<?php
$result = $converter->processVideo('https://www.youtube.com/watch?v=VIDEO_ID');
// Get individual properties
$title = $result->getTitle(); // Video title
$outputPath = $result->getOutputPath(); // Full path to converted file
$videoId = $result->getVideoId(); // Unique conversion ID
$format = $result->getFormat(); // Audio format (mp3, wav, etc.)
$size = $result->getSize(); // File size in bytes
$duration = $result->getDuration(); // Duration in seconds
// Convert to array for JSON/API responses
$data = $result->toArray();
echo json_encode($data, JSON_PRETTY_PRINT);
// Output:
// {
// "outputPath": "/path/to/downloads/video_title.mp3",
// "title": "Video Title",
// "videoId": "video_123456",
// "format": "mp3",
// "size": 5242880,
// "duration": 240
// }
Binary Management
Check Binary Availability
<?php
use Darkweb\YoutubeMp3Converter\Converter\Util\PlatformDetector;
// Check if required binaries are available
$requirements = PlatformDetector::checkRequirements(['yt-dlp', 'ffmpeg']);
foreach ($requirements as $binary => $info) {
if ($info['exists']) {
echo "✓ {$binary}: Available at {$info['path']}\n";
} else {
echo "✗ {$binary}: Not found\n";
echo "Installation instructions:\n";
echo $info['instructions'] . "\n\n";
}
}
Use Custom Binary Paths (Advanced)
<?php
// If you have binaries in custom locations
try {
$ytdlpPath = PlatformDetector::getExecutablePath('yt-dlp', '/usr/local/bin/yt-dlp');
$ffmpegPath = PlatformDetector::getExecutablePath('ffmpeg', '/opt/ffmpeg/bin/ffmpeg');
echo "Using custom yt-dlp: {$ytdlpPath}\n";
echo "Using custom ffmpeg: {$ffmpegPath}\n";
// The converter will automatically use these paths
$converter = new YouTubeConverter(
outputPath: './downloads',
tempPath: './temp',
progress: new FileProgress('./progress')
);
} catch (\RuntimeException $e) {
echo "Custom binary path error: " . $e->getMessage() . "\n";
}
Multiple Conversions
Sequential Processing
<?php
$urls = [
'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'
];
$converter = new YouTubeConverter(
outputPath: './downloads',
tempPath: './temp',
progress: new FileProgress('./progress')
);
$results = [];
foreach ($urls as $url) {
try {
echo "Converting: {$url}\n";
$result = $converter->processVideo($url);
$results[] = [
'url' => $url,
'success' => true,
'title' => $result->getTitle(),
'file' => $result->getOutputPath()
];
echo "✓ Completed: {$result->getTitle()}\n\n";
} catch (ConverterException $e) {
$results[] = [
'url' => $url,
'success' => false,
'error' => $e->getMessage()
];
echo "✗ Failed: {$e->getMessage()}\n\n";
}
}
// Summary
echo "Conversion Summary:\n";
$successful = array_filter($results, fn($r) => $r['success']);
echo "Successful: " . count($successful) . "/" . count($results) . "\n";
Best Practices
1. Always Use Try-Catch
try {
$result = $converter->processVideo($url);
// Process result
} catch (ConverterException $e) {
// Handle conversion errors
} catch (\Exception $e) {
// Handle unexpected errors
}
2. Validate URLs Before Processing
function isValidYouTubeUrl(string $url): bool
{
return preg_match('/^https?:\/\/(www\.)?(youtube\.com|youtu\.be)\//', $url) === 1;
}
if (isValidYouTubeUrl($url)) {
$result = $converter->processVideo($url);
} else {
echo "Invalid YouTube URL\n";
}
3. Set Reasonable Timeouts
// For long videos, consider increasing process timeouts
ini_set('max_execution_time', 300); // 5 minutes
// The library handles timeouts internally, but you may need
// to adjust PHP's execution time for very long videos
4. Clean Up Resources
// The library automatically cleans up temporary files,
// but you can also manually clean old downloads
function cleanOldDownloads(string $directory, int $maxAge = 86400): void
{
$files = glob($directory . '/*');
$now = time();
foreach ($files as $file) {
if (is_file($file) && ($now - filemtime($file)) > $maxAge) {
unlink($file);
echo "Cleaned up old file: " . basename($file) . "\n";
}
}
}
// Clean files older than 24 hours
cleanOldDownloads('./downloads');
Next Steps
- Advanced Configuration - Quality settings, metadata, and more
- Examples - Real-world usage scenarios
- API Reference - Complete method documentation
- Troubleshooting - Common issues and solutions