使用 php 设置 mp3 的专辑封面

发布于 2024-07-26 22:31:26 字数 53 浏览 5 评论 0原文

我正在寻找使用 PHP 设置 mp3 专辑艺术的最佳或任何方法。

建议?

I am looking for the best or any way to set the Album Art of mp3s using PHP.

Suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

他不在意 2024-08-02 22:31:27

我不只是分享专辑封面更新的代码,我将在这里发布 getID3 的整个 MP3 包装类,以便您可以随心所欲地使用。

用法

$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();

<?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'=> '[email protected]', '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]];
    }


}

注意

目前还没有任何错误处理代码。 目前,当我尝试运行任何操作时,我只是依赖异常。
请随意修改并适合使用。 需要 PHP GETID3

Rather than just share the code for album art update, I an going to post my entire MP3 wrapper class of getID3 here so you can use as you wish

Usage

$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();

Class

<?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'=> '[email protected]', '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]];
    }


}

Note

There isn't any error handling code yet. Currently, I am just relying on exceptions when I try to run any operations.
Feel free to modify and use as fit. Requires PHP GETID3

属性 2024-08-02 22:31:27

使用 Composer 安装 getId3 composer require james-heinrich/getid3
然后使用此代码更新您的 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));
}

Install getId3 using composer composer require james-heinrich/getid3
Then Use this code to update your id3 tags

// 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));
}
莫相离 2024-08-02 22:31:27

您可以查看 getID3() 项目。 我不能保证它可以处理图像,但它确实声称能够为 MP3 写入 ID3 标签,所以我认为这将是您最好的选择。

You can look into the getID3() project. I can't promise that it can handle images but it does claim to be able to write ID3 tags for MP3s so I think it will be your best bet.

烟雨扶苏 2024-08-02 22:31:27

以下是使用 getID3 添加图像和 ID3 数据的基本代码。 (@frostymarvelous 的包装器包含等效的代码,但我认为展示基础知识很有帮助。)

<?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'
            )
        )
    );
?>

Here is the basic code for adding an image and ID3 data using getID3. (@frostymarvelous' wrapper includes equivalent code, however I think that it is helpful to show the basics.)

<?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'
            )
        )
    );
?>
分分钟 2024-08-02 22:31:27

@carrp $Tagdata 代码将无法工作,除非每个值属性都是一个数组,例如

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

@carrp the $Tagdata code won't work unless each value property is an array e.g.

$TagData = array(
    'title' => ['My Title'],
    'artist' => ['My Artist'],        
    'attached_picture' => array(   
        array (
            'data'=> $pictureFile,
            'picturetypeid'=> 3,
            'mime'=> 'image/jpeg',
            'description' => 'My Picture'
        )
    )
);
遇到 2024-08-02 22:31:27

使用 PHP 的这个内置函数,

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

Use this inbuilt function of PHP,

<?php
    $tag = id3_get_tag( "path/to/example.mp3" );
    print_r($tag);
?>
浅忆 2024-08-02 22:31:27

我认为 PHP 不可能做到这一点。 我的意思是,我认为一切皆有可能,但它可能不是原生 PHP 解决方案。 从 PHP 文档,我认为唯一的项目可以更新的有:

  • 标题
  • 艺术家
  • 专辑
  • 年份
  • 流派
  • 评论
  • 曲目

对不起,伙计。 也许 Perl、Python 或 Ruby 可能有一些解决方案。

我不确定你是否熟悉 Perl(我个人不喜欢它,但是,它擅长做这样的事情......)。 下面的脚本似乎能够在 MP3 中提取和编辑专辑封面: http: //www.plunder.com/-download-66279.htm

I don't think it's really possible with PHP. I mean, I suppose anything is possible but it may not be a native PHP solution. From the PHP Docs, I think the only items that can be updated are:

  • Title
  • Artists
  • Album
  • Year
  • Genre
  • Comment
  • Track

Sorry man. Maybe Perl, Python, or Ruby might have some solution.

I'm not sure if you are familiar with Perl (I personally don't like it, but, it's good at things like this...). Here's a script that seems to be able to pull in and edit album art in an MP3: http://www.plunder.com/-download-66279.htm

离笑几人歌 2024-08-02 22:31:26

专辑封面是根据 ID3v2 规范标识为“附加图片”的数据框,并且
getID3() 现在只是用纯 PHP 在 ID3v2 中写入所有可能的数据帧的一种方法。

看这个来源:
http://getid3.sourceforge.net/source/write.id3v2.phps

在源中搜索这段文字:

// 4.14  APIC Attached picture

有一段代码负责编写专辑封面。

另一种方法似乎不像纯 PHP 慢,是使用一些外部应用程序,该应用程序将由 PHP 脚本启动。 如果您的服务设计为在高负载下工作,二进制编译工具将是更好的解决方案。

Album art is a data frame identified as “Attached picture” due ID3v2 specification, and
getID3() now is only one way to write all possible data frames in ID3v2 with pure PHP.

Look at this source:
http://getid3.sourceforge.net/source/write.id3v2.phps

Search for this text in the source:

// 4.14  APIC Attached picture

there's a piece of code responsible for writing album art.

Another way, that seems to be not as slow as pure PHP, is to use some external application, that will be launched by PHP script. If your service designed to work under a high load, binary compiled tool will be a better solution.

温柔戏命师 2024-08-02 22:31:26

更好(更快)的方法是通过外部应用程序和 PHP exec() 函数来执行命令。 我会推荐 eyeD3

A better (faster) way to do this would be through an external application and the PHP exec() function to fun a command. I would recommend eyeD3.

风和你 2024-08-02 22:31:26

不确定这仍然是一个问题,但是:

令人惊讶的完整 getid3() (http://getid3.org) 项目将解决你所有的问题。 看看这个< /a> 论坛帖子以获取更多信息。

Not sure this is still an issue but:

the amazingly complete getid3() (http://getid3.org) project will solve all your problems. Check out this forum post for more info.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文