PHP code example of darkwob / youtube-mp3-converter

1. Go to this page and download the library: Download darkwob/youtube-mp3-converter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

darkwob / youtube-mp3-converter example snippets


use Darkwob\YoutubeMp3Converter\Converter\YouTubeConverter;
use Darkwob\YoutubeMp3Converter\Converter\Options\ConverterOptions;
use Darkwob\YoutubeMp3Converter\Progress\FileProgress;

// Initialize progress tracker
$progress = new FileProgress(__DIR__ . '/progress');

// Configure conversion options
$options = new ConverterOptions();
$options->setAudioFormat('mp3')->setAudioQuality(0); // Highest quality

// Initialize converter (binaries auto-detected or specify paths)
$converter = new YouTubeConverter(
    __DIR__ . '/downloads',     // Output directory
    __DIR__ . '/temp',          // Temporary directory
    $progress,                  // Progress tracker
    $options,                   // Converter options (optional)
    __DIR__ . '/bin'            // Binary path (optional, auto-detected if not provided)
);

// Convert a single video
try {
    $result = $converter->processVideo('https://www.youtube.com/watch?v=VIDEO_ID');
    
    echo "Converted: " . $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();
}

// Convert entire YouTube playlist
try {
    $results = $converter->processPlaylist('https://www.youtube.com/playlist?list=PLAYLIST_ID');
    
    echo "Converted " . count($results) . " videos from playlist:\n";
    foreach ($results as $result) {
        echo "- " . $result->getTitle() . " (" . $result->getFormat() . ")\n";
    }
    
} catch (ConverterException $e) {
    echo "Error: " . $e->getMessage();
}

// Convert specific playlist items (e.g., videos 1-5 and 10)
$options->setPlaylistItems('1-5,10');
$converter = new YouTubeConverter($outputDir, $tempDir, $progress, $options);

$results = $converter->processPlaylist('https://www.youtube.com/playlist?list=PLAYLIST_ID');

// Automatically detect and process single videos or playlists
$url = 'https://www.youtube.com/watch?v=VIDEO_ID'; // or playlist URL

if ($converter->isPlaylistUrl($url)) {
    $results = $converter->processPlaylist($url);
    echo "Processed " . count($results) . " videos from playlist\n";
} else {
    $result = $converter->processVideo($url);
    echo "Processed single video: " . $result->getTitle() . "\n";
}

use Darkwob\YoutubeMp3Converter\Converter\Options\ConverterOptions;

$options = new ConverterOptions();
$options
    ->setAudioFormat('mp3')                    // mp3, wav, aac, m4a, opus, vorbis, flac
    ->setAudioQuality(0)                       // 0 (highest) to 9 (lowest) quality
    ->setPlaylistItems('1-10')                 // Process specific playlist items
    ->setDateAfter('20240101')                 // Videos after this date
    ->setDateBefore('20241231')                // Videos before this date
    ->setFileSizeLimit('100M')                 // Maximum file size
    ->setOutputTemplate('%(title)s.%(ext)s')   // Custom output template
    ->setProxy('socks5://127.0.0.1:1080')      // Proxy configuration
    ->setRateLimit(500)                        // Download speed limit (KB/s)
    ->enableThumbnail(true)                    // Embed thumbnail
    ->setMetadata([                            // Custom metadata
        'artist' => 'Artist Name',
        'album' => 'Album Name'
    ]);

$converter = new YouTubeConverter($outputDir, $tempDir, $progress, $options);

use Darkwob\YoutubeMp3Converter\Converter\Remote\RemoteConverter;

$remote = new RemoteConverter(
    'https://api.converter.com',
    'your-api-token'
);

// Async conversion
$jobId = $remote->startConversion($url, $options);

// Check progress
$status = $remote->getProgress($jobId);

// Download when ready
if ($status['status'] === 'completed') {
    $remote->downloadFile($jobId, 'output.mp3');
}

use Darkwob\YoutubeMp3Converter\Progress\RedisProgress;

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$progress = new RedisProgress($redis, 'converter:', 3600);

// Track progress
$progress->update('video123', 'downloading', 50, 'Downloading video...');

// Get progress
$status = $progress->get('video123');
echo "Progress: {$status['progress']}%\n";
echo "Status: {$status['status']}\n";
echo "Message: {$status['message']}\n";

use Darkwob\YoutubeMp3Converter\Converter\Exceptions\{
    ConverterException,
    InvalidUrlException,
    BinaryNotFoundException,
    DirectoryException,
    ProcessException,
    NetworkException
};

try {
    $result = $converter->processVideo($url);
} catch (InvalidUrlException $e) {
    // Handle URL validation errors
    echo "Invalid YouTube URL: " . $e->getMessage();
} catch (BinaryNotFoundException $e) {
    // Handle missing binary errors with installation instructions
    echo "Missing software: " . $e->getMessage();
} catch (DirectoryException $e) {
    // Handle directory creation/permission errors
    echo "Directory error: " . $e->getMessage();
} catch (ProcessException $e) {
    // Handle binary execution errors
    echo "Process error: " . $e->getMessage();
} catch (NetworkException $e) {
    // Handle network/connection errors
    echo "Network error: " . $e->getMessage();
} catch (ConverterException $e) {
    // Handle general conversion errors
    echo "Conversion error: " . $e->getMessage();
}