PHPackages                             darkwob/youtube-mp3-converter - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. darkwob/youtube-mp3-converter

ActiveLibrary[Caching](/categories/caching)

darkwob/youtube-mp3-converter
=============================

A powerful YouTube to MP3 converter with playlist support, progress tracking, and advanced features

v1.2.0(11mo ago)91096[3 issues](https://github.com/darkwob/youtube-mp3-converter/issues)MITPHPPHP &gt;=8.3

Since Dec 8Pushed 11mo ago1 watchersCompare

[ Source](https://github.com/darkwob/youtube-mp3-converter)[ Packagist](https://packagist.org/packages/darkwob/youtube-mp3-converter)[ Docs](https://github.com/darkwob/youtube-mp3-converter)[ RSS](/packages/darkwob-youtube-mp3-converter/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (5)Dependencies (3)Versions (6)Used By (0)

🎵 YouTube to MP3 Converter
==========================

[](#-youtube-to-mp3-converter)

[![PHP Version](https://camo.githubusercontent.com/62aeff98201d8b5641823c0f650139b2e355414fe60cbb72fe705f1c6c55505d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e332d626c7565)](https://camo.githubusercontent.com/62aeff98201d8b5641823c0f650139b2e355414fe60cbb72fe705f1c6c55505d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e332d626c7565)[![Status](https://camo.githubusercontent.com/67ea8d572ec2385f03573ef7af965e14813447a41c9fde846192864702c3a6ea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5374617475732d537461626c652d677265656e)](https://camo.githubusercontent.com/67ea8d572ec2385f03573ef7af965e14813447a41c9fde846192864702c3a6ea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5374617475732d537461626c652d677265656e)[![License](https://camo.githubusercontent.com/5caa455d8debc46fb23abbadb45a733a937f3910a73fc875c2f7820468e1bb54/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e)](https://camo.githubusercontent.com/5caa455d8debc46fb23abbadb45a733a937f3910a73fc875c2f7820468e1bb54/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e)

A powerful and feature-rich YouTube to MP3 converter library for PHP 8.3+ that supports YouTube video conversion with extensive customization options, progress tracking, and Windows compatibility with enhanced binary management.

✨ Key Features
--------------

[](#-key-features)

- 🎵 Convert YouTube videos to multiple audio formats (MP3, AAC, FLAC, WAV, etc.)
- 📋 **Full playlist support** - Convert entire playlists or specific items
- 🎯 **Smart URL detection** - Automatically handles single videos and playlists
- 🎶 **YouTube Music support** - Works with YouTube Music URLs
- 📊 Real-time progress tracking (File-based or Redis)
- 🌐 Remote server conversion support
- 🔒 Clean and modern PHP 8.3+ API with readonly properties
- 🛠️ Extensive configuration options (quality, metadata, thumbnails)
- 🎯 ConversionResult objects for type-safe results
- 🔄 Cross-platform compatibility (Windows, Linux, macOS)
- 🚀 Robust error handling with specific exception types
- 🪟 Enhanced Windows support with path normalization
- 🔧 Intelligent binary detection and management
- 📁 Advanced directory and process management

🚀 Installation
--------------

[](#-installation)

```
composer require darkwob/youtube-mp3-converter
```

### Requirements

[](#requirements)

- PHP &gt;= 8.3 (required)
- JSON extension
- FFmpeg (required for audio conversion)
- yt-dlp (required for video downloading)
- Redis (optional, for Redis-based progress tracking)
- Windows: Proper PATH environment or binary placement in project directory

💻 Basic Usage
-------------

[](#-basic-usage)

### Simple Video Conversion

[](#simple-video-conversion)

```
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();
}
```

### Playlist Conversion

[](#playlist-conversion)

```
// 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');
```

### Smart URL Processing

[](#smart-url-processing)

```
// 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";
}
```

### Advanced Configuration

[](#advanced-configuration)

```
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);
```

### Remote Conversion

[](#remote-conversion)

```
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');
}
```

### Progress Tracking with Redis

[](#progress-tracking-with-redis)

```
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";
```

🔧 API Reference
---------------

[](#-api-reference)

### YouTubeConverter Class

[](#youtubeconverter-class)

Main class for video conversion operations.

#### Methods

[](#methods)

- `processVideo(string $url): ConversionResult` - Convert single video
- `processPlaylist(string $playlistUrl): array` - Convert YouTube playlist
- `getVideoInfo(string $url): array` - Get video metadata
- `getPlaylistInfo(string $playlistUrl): array` - Get playlist metadata
- `isPlaylistUrl(string $url): bool` - Check if URL is a playlist
- `extractVideoId(string $url): string` - Extract video ID from URL
- `extractPlaylistId(string $url): string` - Extract playlist ID from URL
- `downloadVideo(string $url, string $id): string` - Download video file (internal)

### ConversionResult Class

[](#conversionresult-class)

Readonly result object returned by `processVideo()`:

- `getOutputPath(): string` - Full path to converted file
- `getTitle(): string` - Video title
- `getVideoId(): string` - Internal process ID
- `getFormat(): string` - Audio format (mp3, aac, etc.)
- `getSize(): int` - File size in bytes
- `getDuration(): float` - Duration in seconds
- `toArray(): array` - Convert to array

### ConverterOptions Class

[](#converteroptions-class)

Configuration options for the converter.

#### Methods

[](#methods-1)

- `setAudioFormat(string $format): self` - Set output audio format
- `setAudioQuality(int $quality): self` - Set audio quality (0-9)
- `setPlaylistItems(string $items): self` - Set playlist items to process
- `setDateAfter(string $date): self` - Set start date filter (YYYYMMDD)
- `setDateBefore(string $date): self` - Set end date filter (YYYYMMDD)
- `setFileSizeLimit(string $limit): self` - Set maximum file size
- `setOutputTemplate(string $template): self` - Set output filename template
- `setProxy(string $proxy): self` - Set proxy server
- `setRateLimit(int $limit): self` - Set download speed limit (KB/s)
- `enableThumbnail(bool $enable): self` - Enable thumbnail embedding
- `setMetadata(array $metadata): self` - Set audio metadata

### RemoteConverter Class

[](#remoteconverter-class)

Handle remote conversion operations.

#### Methods

[](#methods-2)

- `processVideo(string $url): ConversionResult` - Process video on remote server
- `getVideoInfo(string $url): array` - Get video info from remote server
- `downloadVideo(string $url, string $id): string` - Download from remote server

### Progress Tracking

[](#progress-tracking)

Both `FileProgress` and `RedisProgress` implement `ProgressInterface`:

#### Methods

[](#methods-3)

- `update(string $id, string $status, float $progress, string $message): void`
- `get(string $id): ?array`
- `remove(string $id): void`

🛠️ Error Handling
-----------------

[](#️-error-handling)

The package uses specific exception types for better error handling:

```
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();
}
```

🔒 Security
----------

[](#-security)

- Input validation and URL sanitization
- Safe file handling with proper permissions
- Proxy support for restricted networks
- Cross-platform path handling with Windows normalization
- Secure temporary file management with automatic cleanup
- Binary path validation and security checks
- Windows environment variable handling

📝 License
---------

[](#-license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

📚 Documentation
---------------

[](#-documentation)

For more detailed documentation and examples, visit our [Wiki](https://github.com/darkwob/youtube-mp3-converter/wiki).

⚠️ Disclaimer
-------------

[](#️-disclaimer)

This package is for educational purposes only. Please respect YouTube's terms of service and copyright laws when using this package.

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance45

Moderate activity, may be stable

Popularity20

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~56 days

Total

5

Last Release

339d ago

PHP version history (2 changes)v1.0.0PHP &gt;=7.4

v1.1.1PHP &gt;=8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/58f22e0e79b0893f563d68edc2d1b79213c2ce4d8775b5f230d8eb0d7f40ddf7?d=identicon)[darkwob](/maintainers/darkwob)

---

Top Contributors

[![darkwob](https://avatars.githubusercontent.com/u/71833890?v=4)](https://github.com/darkwob "darkwob (18 commits)")

---

Tags

asyncredisconverteryoutubedownloadermp3playlistyoutube musicprogress-trackingaudio-converter

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/darkwob-youtube-mp3-converter/health.svg)

```
[![Health](https://phpackages.com/badges/darkwob-youtube-mp3-converter/health.svg)](https://phpackages.com/packages/darkwob-youtube-mp3-converter)
```

###  Alternatives

[tempest/framework

The PHP framework that gets out of your way.

2.2k31.1k12](/packages/tempest-framework)[drupal/core

Drupal is an open source content management platform powering millions of websites and applications.

19564.8M1.6k](/packages/drupal-core)[spatie/laravel-export

Create a static site bundle from a Laravel app

672139.5k6](/packages/spatie-laravel-export)[open-dxp/opendxp

Content &amp; Product Management Framework (CMS/PIM)

9317.2k55](/packages/open-dxp-opendxp)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
