Files
ben 67c1941833 Support common audio formats beyond MP3.
Accept WAV, OGG, FLAC, M4A, and related uploads, and read metadata from non-ID3 tag formats.
2026-08-12 14:32:56 +02:00

108 lines
2.7 KiB
PHP

<?php
namespace App\Services;
use Carbon\Carbon;
use getID3;
class Mp3MetadataService
{
/**
* Extract tags and duration from a common audio file (MP3, WAV, OGG, FLAC, M4A, etc.).
*
* @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 = $this->preferredTags($info);
$title = $this->firstTag($tags, 'title');
$artist = $this->firstTag($tags, 'artist');
$album = $this->firstTag($tags, 'album');
$year = $this->firstTag($tags, 'year')
?? $this->firstTag($tags, 'date')
?? $this->firstTag($tags, 'recording_time')
?? $this->firstTag($tags, 'creation_date');
$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,
];
}
/**
* Pick the richest tag set getID3 found for this format.
*
* @param array<string, mixed> $info
* @return array<string, mixed>
*/
private function preferredTags(array $info): array
{
$priority = [
'id3v2',
'id3v1',
'vorbiscomment',
'quicktime',
'riff',
'asf',
'ape',
'matroska',
];
foreach ($priority as $format) {
if (! empty($info['tags'][$format]) && is_array($info['tags'][$format])) {
return $info['tags'][$format];
}
}
if (! empty($info['comments']) && is_array($info['comments'])) {
return $info['comments'];
}
return [];
}
/**
* @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;
}
}