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

PHP library for reading and parsing audio/video file metadata. Extracts tags (ID3, APE, Lyrics3) and technical info from many formats including MP3, AAC/MP4, FLAC, Ogg (Vorbis/Opus), WAV/AIFF, AVI/ASF, MKV, and more.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation

    composer require james-heinrich/getid3
    

    Ensure your PHP version meets requirements (≥5.3.0 for Laravel compatibility).

  2. Basic Usage

    use getID3\getid3;
    
    $getID3 = new getid3();
    $fileInfo = $getID3->analyze('path/to/audio.mp3');
    
    • First Use Case: Extract metadata from a single file (e.g., title, artist, duration).
    • Key Output: $fileInfo is a nested associative array (see /structure.txt in the package).
  3. Where to Look First

    • Demos: Run /demos/demo.basic.php to see minimal parsing.
    • Structure: Review /structure.txt for the returned data schema.
    • Documentation: Check the official site for format-specific quirks.

Implementation Patterns

Core Workflows

  1. Batch Processing

    $files = Storage::files('media/audio');
    $metadata = [];
    foreach ($files as $file) {
        $getID3 = new getid3();
        $metadata[$file] = $getID3->analyze(storage_path('app/' . $file));
    }
    
    • Tip: Use Laravel’s Storage facade for filesystem access.
  2. Tag Writing

    $getID3->tagging->tag_file(
        'path/to/file.mp3',
        [
            'title' => 'New Title',
            'artist' => 'New Artist',
        ]
    );
    
    • Use Case: Update metadata for uploaded files (e.g., after user edits).
  3. Remote Files

    $tempFile = tempnam(sys_get_temp_dir(), 'getid3_');
    file_put_contents($tempFile, file_get_contents('http://example.com/audio.mp3'));
    $getID3 = new getid3();
    $fileInfo = $getID3->analyze($tempFile);
    unlink($tempFile);
    
    • Laravel Integration: Use Http facade or Storage::disk('s3')->download().
  4. Validation & Error Handling

    try {
        $fileInfo = $getID3->analyze($filePath);
        if (isset($fileInfo['error'])) {
            throw new \Exception('File parsing error: ' . $fileInfo['error'][0]);
        }
    } catch (\Exception $e) {
        Log::error($e->getMessage());
    }
    
    • Laravel Tip: Log errors with Log::error() and return user-friendly messages.

Integration Tips

  • Eloquent Models: Attach metadata to a Media model:
    public function updateFromFile($filePath) {
        $getID3 = new getid3();
        $this->metadata = $getID3->analyze($filePath);
        $this->duration = $this->metadata['playtime_seconds'] ?? 0;
        $this->save();
    }
    
  • Jobs: Use Laravel Queues for long-running scans:
    ScanMediaJob::dispatch($filePath)->onQueue('media');
    
  • Events: Trigger events after metadata extraction:
    event(new MediaMetadataExtracted($fileInfo, $filePath));
    

Gotchas and Tips

Pitfalls

  1. Memory Limits

    • Issue: Large files (e.g., >100MB) may hit PHP’s memory_limit.
    • Fix: Increase memory_limit in php.ini or process files in chunks:
      ini_set('memory_limit', '256M');
      
    • Laravel Tip: Use app('config')->set('memory_limit', '256M') in a service provider.
  2. File Paths & Permissions

    • Issue: getid3 may fail silently if paths are invalid or permissions are denied.
    • Fix: Validate paths and check storage permissions:
      if (!file_exists($filePath) || !is_readable($filePath)) {
          throw new \RuntimeException("File not accessible: {$filePath}");
      }
      
  3. Corrupt Files

    • Issue: Malformed files may throw exceptions (v2.x) or return partial data.
    • Fix: Check for error or warning keys in $fileInfo:
      if (isset($fileInfo['error'])) {
          return response()->json(['error' => 'Invalid file'], 400);
      }
      
  4. Remote File Handling

    • Issue: Downloading remote files can fail due to timeouts or invalid URLs.
    • Fix: Use Laravel’s Http client with retries:
      try {
          $response = Http::timeout(30)->get($remoteUrl);
          file_put_contents($tempFile, $response->body());
      } catch (\Exception $e) {
          Log::error("Failed to download remote file: {$e->getMessage()}");
      }
      
  5. ID3v2 Tag Conflicts

    • Issue: Some MP3 players ignore tags if they’re malformed or duplicated.
    • Fix: Use getid3's built-in validation before writing:
      $getID3->tagging->validate_tags([
          'title' => 'Valid Title',
          'artist' => 'Valid Artist',
      ]);
      

Debugging Tips

  • Enable Verbose Output:

    $getID3->setOption('verbose', true);
    
    • Useful for diagnosing parsing issues.
  • Inspect Raw Data:

    dd($fileInfo); // Laravel's dump and die
    
    • Compare against /structure.txt to understand missing fields.
  • Check File Formats:

    if (isset($fileInfo['mime_type'])) {
        Log::debug("File MIME type: {$fileInfo['mime_type']}");
    }
    

Extension Points

  1. Custom Metadata Fields

    • Extend the returned structure by adding a post-processing step:
      $fileInfo['custom'] = [
          'bitrate_kbps' => $fileInfo['audio']['bitrate_mode'] ?? 0,
          'is_vbr' => $fileInfo['audio']['bitrate_mode'] === 'vbr',
      ];
      
  2. Plugin System

    • Override or extend parsers by modifying getid3/module.tag.id3v2.php (advanced).
    • Laravel Tip: Use service providers to bind custom parsers:
      $this->app->singleton('getid3.parser.custom', function () {
          return new CustomParser();
      });
      
  3. Caching

    • Cache parsed metadata to avoid reprocessing:
      $cacheKey = 'media.metadata.' . md5($filePath);
      $fileInfo = Cache::remember($cacheKey, now()->addHours(1), function () use ($getID3, $filePath) {
          return $getID3->analyze($filePath);
      });
      
  4. Laravel Service Provider

    • Bind getid3 as a singleton for dependency injection:
      $this->app->singleton('getid3', function () {
          return new \getID3\getid3();
      });
      
    • Usage in controllers:
      public function __construct(private getid3 $getID3) {}
      

Config Quirks

  • Default Options:
    $getID3->setOption('useid3v2', true); // Prefer ID3v2 over ID3v1
    $getID3->setOption('skip_analyze', ['mime', 'filename']); // Skip expensive checks
    
  • Performance:
    • Disable unnecessary modules (e.g., video parsing for audio-only files):
      $getID3->setOption('skip_analyze', ['video']);
      
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai