Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Getid3 Laravel Package

james-heinrich/getid3

getID3() is a PHP library to read and parse audio/video metadata and tags (ID3, APE, Lyrics3, etc.) across many formats including MP3, FLAC, Ogg, MP4/AAC, WAV, AVI, MKV, ASF/WMV/WMA, and more.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install via Composer:
    composer require james-heinrich/getid3
    
  2. Basic Usage:
    use getID3\getID3;
    
    $getID3 = new getID3();
    $fileInfo = $getID3->analyze('path/to/your/file.mp3');
    
  3. First Use Case: Extract metadata from an uploaded audio file in a Laravel controller:
    public function uploadAudio(Request $request) {
        $request->validate(['audio' => 'required|file']);
        $file = $request->file('audio');
        $filePath = $file->getRealPath();
    
        $getID3 = new getID3();
        $metadata = $getID3->analyze($filePath);
    
        // Use metadata (e.g., save to DB)
        return response()->json($metadata);
    }
    

Implementation Patterns

Common Workflows

  1. Batch Processing: Use Laravel's Storage facade to process files in bulk:

    use Illuminate\Support\Facades\Storage;
    
    $files = Storage::disk('public')->files('audio');
    foreach ($files as $file) {
        $getID3 = new getID3();
        $metadata = $getID3->analyze(storage_path('app/public/' . $file));
        // Process metadata (e.g., update DB)
    }
    
  2. Tag Writing: Update metadata for an existing file:

    $getID3 = new getID3();
    $fileInfo = $getID3->analyze('file.mp3');
    
    // Modify tags
    $fileInfo['id3v2']['tags']['title'] = ['text' => 'New Title'];
    $getID3->tag_write($fileInfo, 'file.mp3');
    
  3. Remote Files: Stream remote files to a temporary location:

    $remoteUrl = 'https://example.com/audio.mp3';
    $tempPath = tempnam(sys_get_temp_dir(), 'getid3_');
    file_put_contents($tempPath, file_get_contents($remoteUrl));
    
    $getID3 = new getID3();
    $metadata = $getID3->analyze($tempPath);
    unlink($tempPath); // Cleanup
    
  4. Laravel Service Provider: Bind getID3 to the container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->bind(getID3::class, function () {
            return new getID3();
        });
    }
    

    Usage in controllers:

    use getID3;
    
    public function __construct(private getID3 $getID3) {}
    
  5. Queue Jobs: Offload metadata extraction to a queue (e.g., metadata-extract job):

    // app/Jobs/ExtractMetadata.php
    public function handle() {
        $filePath = storage_path('app/uploads/' . $this->fileName);
        $metadata = (new getID3())->analyze($filePath);
        // Save to DB or process further
    }
    

Gotchas and Tips

Pitfalls

  1. Memory Limits:

    • Large files (e.g., >100MB) may hit PHP's memory_limit. Increase it in php.ini or dynamically:
      ini_set('memory_limit', '256M');
      
    • Use getID3::MPEG_streamSeek() for partial scans if full analysis is unnecessary.
  2. File Paths:

    • Always use absolute paths (e.g., storage_path('file.mp3')) to avoid issues with relative paths.
    • Remote files must be downloaded locally first; getID3 does not support direct HTTP/FTP analysis.
  3. Error Handling:

    • Check for ['error'] or exceptions in getID3 v2.x:
      try {
          $metadata = $getID3->analyze($filePath);
      } catch (\Exception $e) {
          Log::error("getID3 error: " . $e->getMessage());
      }
      
  4. Tag Writing:

    • Writing tags may corrupt files if done incorrectly. Test on copies first.
    • Not all formats support writing (e.g., WAV may not support ID3 tags).
  5. File Size Limits:

    • 32-bit PHP cannot fully parse files >2GB. Use 64-bit PHP or avoid such files.
  6. Encoding Issues:

    • Metadata fields (e.g., title, artist) may contain non-UTF-8 characters. Normalize with:
      mb_convert_encoding($metadata['id3v2']['tags']['title'][0], 'UTF-8');
      

Debugging Tips

  1. Inspect Raw Data: Dump the full metadata structure to debug:

    dd($getID3->analyze($filePath));
    
    • Key sections: ['id3v1'], ['id3v2'], ['playtime_string'], ['audio'].
  2. Check File Validity: Use getID3::MPEG_streamSeek() to verify file integrity before full analysis:

    $getID3->MPEG_streamSeek($filePath, 0);
    if ($getID3->error) {
        throw new \Exception("Invalid MP3 file");
    }
    
  3. Log Warnings: Capture warnings for problematic files:

    $metadata = $getID3->analyze($filePath);
    if (isset($metadata['warning'])) {
        Log::warning("File warnings: " . implode(', ', $metadata['warning']));
    }
    

Extension Points

  1. Custom Metadata Fields: Extend the metadata structure by adding custom logic post-analysis:

    $metadata['custom'] = [
        'bitrate_kbps' => $metadata['audio']['bitrate_mode'] ?? 0,
        'duration_seconds' => $metadata['playtime_seconds'] ?? 0,
    ];
    
  2. Laravel Observers: Trigger actions on file uploads via observers:

    // app/Observers/AudioObserver.php
    public function saved($model) {
        $metadata = (new getID3())->analyze($model->path);
        $model->updateMetadata($metadata);
    }
    
  3. Artisan Commands: Create a CLI tool for bulk metadata extraction:

    php artisan metadata:extract storage/app/uploads
    
    // app/Console/Commands/ExtractMetadata.php
    public function handle() {
        $files = Storage::files($this->argument('directory'));
        foreach ($files as $file) {
            $metadata = (new getID3())->analyze(storage_path('app/' . $file));
            // Process or log metadata
        }
    }
    
  4. API Responses: Normalize metadata for API responses:

    public function getMetadata($filePath) {
        $metadata = (new getID3())->analyze($filePath);
        return [
            'title' => $metadata['id3v2']['tags']['title'][0] ?? null,
            'artist' => $metadata['id3v2']['tags']['artist'][0] ?? null,
            'duration' => $metadata['playtime_seconds'] ?? 0,
        ];
    }
    
  5. Caching: Cache metadata to avoid reprocessing:

    $cacheKey = 'metadata:' . md5($filePath);
    $metadata = Cache::remember($cacheKey, now()->addHours(1), function () use ($filePath) {
        return (new getID3())->analyze($filePath);
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport