Pregunta

Estoy buscando la mejor o que de cualquier forma para establecer el Arte del Álbum de mp3 mediante PHP.

Sugerencias?

¿Fue útil?

Solución

arte Album es una trama de datos identificado como “imagen anexa” especificación debido ID3v2, y getID3 () ahora es sólo una manera de escribir todas las posibles tramas de datos en ID3v2 con PHP puro.

Mira esta fuente: http://getid3.sourceforge.net/source/write.id3v2.phps

Búsqueda de este texto en la fuente:

// 4.14  APIC Attached picture

hay una pieza de código responsable de escribir la portada del álbum.

Otra forma, que parece no ser tan lento como PHP puro, es utilizar alguna aplicación externa, que será lanzado por el script PHP. Si su servicio diseñado para trabajar bajo una carga alta, herramienta binario compilado será una solución mejor.

Otros consejos

Una manera mejor (más rápido) para hacer esto sería a través de una aplicación externa y el ejecutivo de PHP () para divertirse un comando. Yo recomendaría eyeD3 .

No está seguro de esto sigue siendo un problema, pero:

proyecto

la getid3 increíblemente completa () ( http://getid3.org ) va a resolver todos sus problemas. Echa un vistazo a este mensaje en el foro de más información.

Instalar getid3 usando composer require james-heinrich/getid3 compositor A continuación, utilice este código para actualizar sus etiquetas ID3

// Initialize getID3 engine
$getID3 = new getID3;

// Initialize getID3 tag-writing module
$tagwriter = new getid3_writetags;
$tagwriter->filename = 'path/to/file.mp3';
$tagwriter->tagformats = array('id3v2.4');
$tagwriter->overwrite_tags    = true;
$tagwriter->remove_other_tags = true;
$tagwriter->tag_encoding      = 'UTF-8';

$pictureFile = file_get_contents("path/to/image.jpg");

$TagData = array(
    'title' => array('My Title'),
    'artist' => array('My Artist'),
    'album' => array('This Album'),
    'comment' => array('My comment'),
    'year' => array(2018),
    'attached_picture' => array(
        array (
            'data'=> $pictureFile,
            'picturetypeid'=> 3,
            'mime'=> 'image/jpeg',
            'description' => 'My Picture'
        )
    )
);

$tagwriter->tag_data = $TagData;

// write tags
if ($tagwriter->WriteTags()){
    return true;
}else{
    throw new \Exception(implode(' : ', $tagwriter->errors));
}

Usted puede mirar en el getID3 () proyecto. No puedo prometer que puede manejar imágenes, pero tiene la pretensión de ser capaz de escribir las etiquetas ID3 para archivos MP3 así que creo que va a ser su mejor apuesta.

En lugar de simplemente compartir el código para la carátula del álbum actualización, una que va a publicar mi todo MP3 clase de contenedor de getID3 aquí, así que usted puede utilizar como desee

El uso de

$mp3 = new Whisppa\Music\MP3($mp3_filepath);

//Get data
$mp3->title
$mp3->artist
$mp3->album
$mp3->genre

//set properties
$mp3->year = '2014';

//change album art
$mp3->set_art(file_get_contents($pathtoimage), 'image/jpeg', 'New Caption');//sets front album art

//save new details
$mp3->save();

Clase

<?php

namespace Whisppa\Music;

class MP3
{
    protected static $_id3;

    protected $file;
    protected $id3;
    protected $data     = null;


    protected $info =  ['duration'];
    protected $tags =  ['title', 'artist', 'album', 'year', 'genre', 'comment', 'track', 'attached_picture', 'image'];
    protected $readonly_tags =  ['attached_picture', 'comment', 'image'];
                                //'popularimeter' => ['email'=> 'music@whisppa.com', 'rating'=> 1, 'data'=> 0],//rating: 5 = 255, 4 = 196, 3 = 128, 2 = 64,1 = 1 | data: counter


    public function __construct($file)
    {
        $this->file = $file;
        $this->id3  = self::id3();
    }

    public function update_filepath($file)
    {
        $this->file = $file;
    }

    public function save()
    {
        $tagwriter = new \GetId3\Write\Tags;
        $tagwriter->filename = $this->file;
        $tagwriter->tag_encoding = 'UTF-8';
        $tagwriter->tagformats = ['id3v2.3', 'id3v1'];
        $tagwriter->overwrite_tags = true;
        $tagwriter->remove_other_tags = true;

        $tagwriter->tag_data = $this->data;

        // write tags
        if ($tagwriter->WriteTags())
            return true;
        else
            throw new \Exception(implode(' : ', $tagwriter->errors));
    }


    public static function id3()
    {
        if(!self::$_id3)
            self::$_id3 = new \GetId3\GetId3Core;

        return self::$_id3;
    }

    public function set_art($data, $mime = 'image/jpeg', $caption = 'Whisppa Music')
    {
        $this->data['attached_picture'] = [];

        $this->data['attached_picture'][0]['data']            = $data;
        $this->data['attached_picture'][0]['picturetypeid']   = 0x03;    // 'Cover (front)'    
        $this->data['attached_picture'][0]['description']     = $caption;
        $this->data['attached_picture'][0]['mime']            = $mime;

        return $this;
    }

    public function __get($key)
    {
        if(!in_array($key, $this->tags) && !in_array($key, $this->info) && !isset($this->info[$key]))
            throw new \Exception("Unknown property '$key' for class '" . __class__ . "'");

        if($this->data === null)
            $this->analyze();

        if($key == 'image')
            return isset($this->data['attached_picture']) ? ['data' => $this->data['attached_picture'][0]['data'], 'mime' => $this->data['attached_picture'][0]['mime']] : null;
        else if(isset($this->info[$key]))
            return $this->info[$key];
        else
            return isset($this->data[$key]) ? $this->data[$key][0] : null;
    }

    public function __set($key, $value)
    {
        if(!in_array($key, $this->tags))
            throw new \Exception("Unknown property '$key' for class '" . __class__ . "'");
        if(in_array($key, $this->readonly_tags))
            throw new \Exception("Tying to set readonly property '$key' for class '" . __class__ . "'");

        if($this->data === null)
            $this->analyze();

        $this->data[$key] = [$value];
    }

    protected function analyze()
    {
        $data = $this->id3->analyze($this->file);

        $this->info =  [
                'duration' => isset($data['playtime_seconds']) ? ceil($data['playtime_seconds']) : 0,
            ];

        $this->data = isset($data['tags']) ? array_intersect_key($data['tags']['id3v2'], array_flip($this->tags)) : [];
        $this->data['comment'] = ['http://whisppa.com'];

        if(isset($data['id3v2']['APIC']))
            $this->data['attached_picture'] = [$data['id3v2']['APIC'][0]];
    }


}

Nota

No hay ningún código de control de errores todavía.Actualmente, estoy simplemente depender de excepciones cuando intento ejecutar cualquier operación.Siéntase libre de modificar y utilizar como ajuste.Requiere PHP GETID3

Este es el código básico para añadir una imagen y datos ID3 utilizando getID3. (Envoltorio @frostymarvelous' incluye código equivalente, sin embargo, creo que es útil para mostrar los conceptos básicos.)

<?php
    // Initialize getID3 engine
    $getID3 = new getID3;

    // Initialize getID3 tag-writing module
    $tagwriter = new getid3_writetags;
    $tagwriter->filename = 'audiofile.mp3';
    $tagwriter->tagformats = array('id3v2.3');
    $tagwriter->overwrite_tags    = true;
    $tagwriter->remove_other_tags = true;
    $tagwriter->tag_encoding      = $TextEncoding;

    $pictureFile=file_get_contents("image.jpg");

    $TagData = array(
        'title' => 'My Title',
        'artist' => 'My Artist',        
        'attached_picture' => array(   
            array (
                'data'=> $pictureFile,
                'picturetypeid'=> 3,
                'mime'=> 'image/jpeg',
                'description' => 'My Picture'
            )
        )
    );
?>

Utilice esta función incorporada de PHP,

<?php
    $tag = id3_get_tag( "path/to/example.mp3" );
    print_r($tag);
?>

No creo que es realmente posible con PHP. Es decir, yo supongo que todo es posible, pero puede que no sea una solución nativa de PHP. Desde el PHP Docs , creo que los únicos elementos que pueden ser actualizados son:

  • Título
  • Artists
  • Album
  • Año
  • Género
  • Comentario
  • Track

Lo siento hombre. Tal vez Perl, Python, Ruby o podría tener alguna solución.

No estoy seguro de si está familiarizado con Perl (personalmente no me gusta, pero, es bueno en este tipo de cosas ...). Aquí hay un guión que parece ser capaz de tirar y editar la portada del álbum en un MP3: http: //www.plunder.com/-download-66279.htm

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top