Files
AndyTranscribe/app/Services/Mp3MetadataService.php
T

78 lines
1.9 KiB
PHP

<?php
namespace App\Services;
use Carbon\Carbon;
use getID3;
class Mp3MetadataService
{
/**
* Extract ID3 and audio metadata from an MP3 file on disk.
*
* @return array{
* title: ?string,
* artist: ?string,
* album: ?string,
* duration_seconds: ?int,
* recorded_at: ?string
* }
*/
public function extract(string $absolutePath): array
{
$analyzer = new getID3;
$info = $analyzer->analyze($absolutePath);
$tags = [];
if (isset($info['tags']['id3v2'])) {
$tags = $info['tags']['id3v2'];
} elseif (isset($info['tags']['id3v1'])) {
$tags = $info['tags']['id3v1'];
}
$title = $this->firstTag($tags, 'title');
$artist = $this->firstTag($tags, 'artist');
$album = $this->firstTag($tags, 'album');
$year = $this->firstTag($tags, 'year') ?? $this->firstTag($tags, 'recording_time');
$duration = isset($info['playtime_seconds'])
? (int) round((float) $info['playtime_seconds'])
: null;
$recordedAt = null;
if (filled($year) && preg_match('/^\d{4}/', $year)) {
try {
$recordedAt = Carbon::parse($year)->toDateTimeString();
} catch (\Throwable) {
$recordedAt = null;
}
}
return [
'title' => $title,
'artist' => $artist,
'album' => $album,
'duration_seconds' => $duration,
'recorded_at' => $recordedAt,
];
}
/**
* @param array<string, mixed> $tags
*/
private function firstTag(array $tags, string $key): ?string
{
if (! isset($tags[$key])) {
return null;
}
$value = $tags[$key];
if (is_array($value)) {
$value = $value[0] ?? null;
}
return filled($value) ? (string) $value : null;
}
}