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 Add the package via Composer:

    composer require james-heinrich/getid3
    

    Requires PHP 5.3+ (or 5.0.5+ for older versions). Ensure your server has at least 8MB memory (12MB recommended for full functionality).

  2. Basic Usage Initialize the library and analyze a file:

    use getID3;
    $getID3 = new getID3;
    $fileInfo = $getID3->analyze('path/to/file.mp3');
    
    • Output: Returns an associative array with metadata (e.g., title, artist, bitrate, duration).
    • First Use Case: Extract metadata from a single file (e.g., for a media library or upload handler).
  3. Key Files to Reference

    • /demos/demo.basic.php: Minimal example for single-file analysis.
    • /demos/demo.browse.php: Directory scanning with recursive file handling.
    • /structure.txt: Documentation of the returned data structure (critical for understanding keys like $fileInfo['id3v2']['title']).

Implementation Patterns

Core Workflows

  1. Single-File Metadata Extraction

    $getID3 = new getID3;
    $fileInfo = $getID3->analyze('audio.mp3');
    // Access nested data:
    $title = $fileInfo['id3v2']['title'][0] ?? $fileInfo['id3v1']['title'];
    $duration = $fileInfo['playtime_seconds'];
    
    • Use Case: Upload handlers, media players, or CMS fields for audio/video.
  2. Batch Processing (Directory Scanning)

    $getID3 = new getID3;
    $files = glob('storage/media/*');
    foreach ($files as $file) {
        $fileInfo = $getID3->analyze($file);
        // Store in DB or cache:
        cache()->put("media:{$file}", $fileInfo);
    }
    
    • Tip: Use demo.browse.php as a template for recursive directory traversal.
  3. Writing Tags (Modifying Files)

    $getID3 = new getID3;
    $getID3->tagging = true; // Enable writing
    $getID3->tagging_options = ['overwrite_tags' => true];
    $getID3->tagging_options['id3v2_version'] = 4;
    $getID3->tagging_options['id3v2_3_flags'] = ['TALB' => 'overwrite'];
    $getID3->tagging_options['id3v2_4_flags'] = ['TIT2' => 'overwrite'];
    
    $fileInfo = $getID3->analyze('audio.mp3');
    $fileInfo['id3v2']['title'] = ['New Title'];
    $getID3->tagging->tag_file('audio.mp3', $fileInfo);
    
    • Use Case: User uploads, bulk metadata updates, or API endpoints for tag editing.
  4. Error Handling

    try {
        $fileInfo = $getID3->analyze('corrupt.mp3');
    } catch (Exception $e) {
        // Log or notify user:
        Log::error("getID3 Error: " . $e->getMessage());
        return response()->json(['error' => 'Invalid file'], 400);
    }
    
    • Note: In getID3 2.x, errors throw exceptions (unlike 1.x, which uses $fileInfo['error']).

Integration Tips

  1. Laravel Service Provider Bind getID3 as a singleton for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton('getID3', function () {
            return new \getID3();
        });
    }
    

    Use in controllers:

    public function uploadMedia(Request $request)
    {
        $getID3 = app('getID3');
        $fileInfo = $getID3->analyze($request->file('media')->path());
        // ...
    }
    
  2. Caching Metadata Cache results to avoid reprocessing:

    $cacheKey = 'media:metadata:' . md5($filePath);
    $fileInfo = cache()->get($cacheKey);
    if (!$fileInfo) {
        $getID3 = new getID3;
        $fileInfo = $getID3->analyze($filePath);
        cache()->put($cacheKey, $fileInfo, now()->addHours(1));
    }
    
  3. Remote Files Download first, then analyze (as shown in the README):

    $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);
    
  4. Database Storage Normalize metadata for storage (e.g., flatten nested arrays):

    $metadata = [
        'title' => $fileInfo['id3v2']['title'][0] ?? null,
        'artist' => $fileInfo['id3v2']['artist'][0] ?? null,
        'duration' => $fileInfo['playtime_seconds'] ?? 0,
        'bitrate' => $fileInfo['audio']['bitrate'] ?? 0,
    ];
    Media::create($metadata);
    

Gotchas and Tips

Pitfalls

  1. Memory Limits

    • Issue: Large files (e.g., 1GB+) may exceed PHP’s memory limit.
    • Fix: Increase memory_limit in php.ini or process files in chunks:
      ini_set('memory_limit', '256M');
      
    • Workaround: Use demo.mysql.php as a reference for chunked processing.
  2. 32-bit PHP Limitations

    • Issue: Files >2GB may fail to parse (e.g., ID3v1/Lyrics3 tags at EOF).
    • Fix: Upgrade to 64-bit PHP or avoid processing oversized files.
  3. Nested Data Structure

    • Issue: Metadata is deeply nested (e.g., $fileInfo['id3v2']['TXXX'][0]['description']).
    • Fix: Use demo.browse.php to inspect your specific file’s structure. Example:
      $title = data_get($fileInfo, 'id3v2.title.0') ?? data_get($fileInfo, 'id3v1.title');
      
  4. Tag Writing Quirks

    • Issue: Writing tags may fail silently or corrupt files.
    • Fix:
      • Enable strict mode: $getID3->tagging_options['strict'] = true;
      • Test on copies first.
      • Check for warnings/errors in $fileInfo['warning'] (1.x) or exceptions (2.x).
  5. Remote File Handling

    • Issue: HTTP/FTP files require local copies, which can fail.
    • Fix: Validate URLs before processing and handle exceptions:
      try {
          $tempFile = tempnam(sys_get_temp_dir(), 'getid3_');
          file_put_contents($tempFile, file_get_contents($remoteUrl));
          $fileInfo = $getID3->analyze($tempFile);
      } catch (\Exception $e) {
          unlink($tempFile ?? null);
          throw $e;
      }
      
  6. Timezone Handling

    • Issue: playtime_seconds may not match user expectations due to timezone offsets.
    • Fix: Convert to UTC or local time:
      $duration = Carbon::createFromTimestamp($fileInfo['playtime_seconds']);
      

Debugging Tips

  1. Inspect Raw Output Dump the full $fileInfo array to debug:

    dd($fileInfo); // Laravel
    // or
    print_r($fileInfo); // Raw PHP
    
    • Focus on: ['error'], ['warning'], and nested keys like ['id3v2'], ['audio'].
  2. Common Errors

    • Could not seek to byte 0: File is locked or unreadable. Fix: Close file handles or check permissions.
    • ID3v2 header not found: File lacks tags or is corrupted. Fix: Use fallback tags (e.g., $fileInfo['id3v1']).
    • Unsupported format: File type not listed in the README. Fix: Check supported formats.
  3. Performance

    • Slow Processing: Disable unused modules (e.g., video parsing for audio files):
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata