I am looking for the best or any way to set the Album Art of mp3s using PHP.
Suggestions?
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.
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.
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.
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'=> '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]];
}
}
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
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));
}
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.
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'
)
)
);
?>
#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'
)
)
);
Use this inbuilt function of PHP,
<?php
$tag = id3_get_tag( "path/to/example.mp3" );
print_r($tag);
?>
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
Related
I am working on audio data in my project and I need to write ID3 tags of my mp3 files, but I am getting this error when calling WriteTags() of getId3 pacakge, I am using this package to write my id3 tags. any one has any idea about how to fix it.
I am getting this output in my code;
filepath : D:/xampp/htdocs/l8/public/storage/songs/newmp3.mp3
Failed to write tags!
Tag format "id3v2" is not allowed on "" files
and my mp3 file remains unmodified.
My controller looks like this
<?php
namespace App\Http\Controllers\Artist;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use App\Models\Track;
use GetId3\GetId3Core as GetId3;
use GetId3\Lib\Helper;
use GetId3\Write\Tags;
class TrackController extends Controller
{
function test(Request $request) {
$getID3 = new GetId3();
$TaggingFormat = 'UTF-8';
$getID3->setOption(array('encoding' => $TaggingFormat));
$tagwriter = new Tags();
$tagwriter->filename = public_path('storage/songs/newmp3.mp3');
$tagwriter->filename = str_replace('\\', '/', $tagwriter->filename);
echo "filepath : " . $tagwriter->filename."<br>";
$tagwriter->tagformats = array('id3v2');
$tagwriter->overwrite_tags = true;
$tagwriter->overwrite_tags = false;
$tagwriter->tag_encoding = $TaggingFormat;
$tagwriter->remove_other_tags = true;
// populate data array
$TagData = array(
'title' => array('My Song'),
'artist' => array('The Artist'),
'album' => array('Greatest Hits'),
'year' => array('2004'),
'genre' => array('Rock'),
'comment' => array('excellent!'),
'track' => array('04/16'),
);
$tagwriter->tag_data = $TagData;
if ($tagwriter->WriteTags()) {
echo 'Successfully wrote tags<br>';
if (!empty($tagwriter->warnings)) {
echo 'There were some warnings:<br>'.implode('<br><br>', $tagwriter->warnings);
}
} else {
echo 'Failed to write tags!<br>'.implode('<br><br>', $tagwriter->errors);
}
}
}
Any help is appreciated.
I tried to write a php script to get cover image and use it as cover image for mp3 file using getid3 php but the cover image is not showing up in media players.
The cover image is showing in windows folders but not in media players icon badge... Also not showing up on google play music on android.
Belows the code.
<?php
$scr1=$_POST['search1'];
$op90=$_POST['search2'];
$kat=$_POST['search3'];
$album=$_POST['search4'];
$genre=$_POST['search5'];
$TextEncoding = 'UTF-8';
$albumPath = "../../image/".$scr1.".jpg"; // path to your image
require_once("../getid3/getid3.php");
// Initialize getID3 engine
$getID3 = new getID3;
$getID3->setOption(array('encoding'=>$TextEncoding));
require_once("../getid3/write.php");
// Initialize getID3 tag-writing module
$tagwriter = new getid3_writetags;
$tagwriter->filename = '../../../public_html/song/'.$op90.'.mp3';
$filename='../../../public_html/song/'.$op90.'.mp3';
//$tagwriter->tagformats = array('id3v1', 'id3v2.3');
$tagwriter->tagformats = array('id3v2.3');
$ThisFileInfo = $getID3->analyze($filename);
// set various options (optional)
$tagwriter->overwrite_tags = true; // if true will erase existing tag data and write only passed data; if false will merge passed data with existing tag data (experimental)
$tagwriter->remove_other_tags = false; // if true removes other tag formats (e.g. ID3v1, ID3v2, APE, Lyrics3, etc) that may be present in the file and only write the specified tag format(s). If false leaves any unspecified tag formats as-is.
$tagwriter->tag_encoding = $TextEncoding;
$tagwriter->remove_other_tags = true;
// populate data array
$TagData = array(
'title' => array($op90),
'artist' => array($kat),
'album' => array($album),
'year' => array($ThisFileInfo['comments_html']['year'][0]),
'genre' => array($genre),
'comment' => array($ThisFileInfo['comments_html']['comment'][0]),
'track' => array($ThisFileInfo['comments_html']['track'][0]),
);
$fd = fopen($albumPath, 'rb');
$APICdata = fread($fd, filesize($albumPath));
fclose($fd);
if($APICdata) {
$TagData += array(
'attached_picture' => array(0 => array(
'data' => $APICdata,
'picturetypeid' => '0x03',
'description' => 'cover',
'mime' => image_type_to_mime_type(#$albumExifType)
))
);
}
$tagwriter->tag_data = $TagData;
// write tags
if ($tagwriter->WriteTags()) {if (!empty($tagwriter->warnings)) {}} else {}
I am having some trouble implementing the pushwoosh class http://astutech.github.io/PushWooshPHPLibrary/index.html. I have everything set up but i am getting an error with the array from the class.
This is the code i provied to the class:
<?php
require '../core/init.php';
//get values from the clientside
$sendID = $_POST['sendID'];
$memID = $_POST['memID'];
//get sender name
$qry = $users->userdata($memID);
$sendName = $qry['name'];
//get receiving token
$qry2 = $users->getTokenForPush($sendID);
$deviceToken = $qry2['token'];
//i have testet that $deviceToken actually returns the $deviceToken so thats not the problem
//this is the array that the php class requires.
$pushArray = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$push->createMessage($pushArray, 'now', null);
?>
And this is the actually code for the createMessage() method
public function createMessage(array $pushes, $sendDate = 'now', $link = null,
$ios_badges = 1)
{
// Get the config settings
$config = $this->config;
// Store the message data
$data = array(
'application' => $config['application'],
'username' => $config['username'],
'password' => $config['password']
);
// Loop through each push and add them to the notifications array
foreach ($pushes as $push) {
$pushData = array(
'send_date' => $sendDate,
'content' => $push['content'],
'ios_badges' => $ios_badges
);
// If a list of devices is specified, add that to the push data
if (array_key_exists('devices', $push)) {
$pushData['devices'] = $push['devices'];
}
// If a link is specified, add that to the push data
if ($link) {
$pushData['link'] = $link;
}
$data['notifications'][] = $pushData;
}
// Send the message
$response = $this->pwCall('createMessage', $data);
// Return a value
return $response;
}
}
Is there a bright mind out there that can tell me whats wrong?
If I understand, your are trying to if your are currently reading the devices sub-array. You should try this:
foreach ($pushes as $key => $push) {
...
// If a list of devices is specified, add that to the push data
if ($key == 'devices') {
$pushData['devices'] = $push['devices'];
}
You iterate over $pushes, which is array('content' => ..., 'devices' => ...). You will first have $key = content, the $key = 'devices'.
It looks like the createMessage function expects an array of messages, but you are passing in one message directly. Try this instead:
$push->createMessage(array($pushArray), 'now', null);
The class is expecting an array of arrays; you are just providing an array.
You could do something like this
//this is the array that the php class requires.
$pushArrayData = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$pushArray[] = $pushArrayData
Will you ever want to handle multiple messages? It makes a difference in how I would do it.
Hello: I have a web form that submits data to my db. I am able to create a signature image and save it within my directory. I want to save/store that signature image in my mysql db along with the record so I can call it later.
Written in CodeIgniter 2.0
here are my model and controller.
public function sig_to_img()
{
if($_POST){
require_once APPPATH.'signature-to-image.php';
$json = $_POST['output'];
$img = sigJsonToImage($json);
imagepng($img, 'signature.png');
imagedestroy($img);
$form = $this->input->post();
var_dump($form);
$this->coapp_mdl->insert_signature($form);
}
}
public function insert_signature($data)
{
$sig_hash = sha1($data['output']);
$created = time();
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'first_name' => $data['fname'],
'last_name' => $data['lname'],
'signator' => $data['name'],
'signature' => $data['output'],
'sig_hash' => $sig_hash,
'ip' => $ip,
'created' => $created
);
return $this->db->insert('signatures', $data);
}
I found the function below on php.net but apparently I am doing something wrong or various things wrong. Does anyone know how to accomplish this functionality?
$imagefile = "changethistogourimage.gif";
$image = imagecreatefromgif($imagefile);
ob_start();
imagepng($image);
$imagevariable = ob_get_contents();
ob_end_clean();
Got it - For those curious here are the changes to my controller:
public function sig_to_img()
{
if($_POST){
require_once APPPATH.'signature-to-image.php';
$json = $_POST['output'];
$img = sigJsonToImage($json);
// Save to file
$file_name = trim(str_replace(" ","_",$_POST['name']));//name to used for filename
imagepng($img, APPPATH."../images/signatures/".$file_name.'.png');
$sig_name = $file_name.'.png'; //pass to model
// Destroy the image in memory when complete
imagedestroy($img);
$form = $this->input->post();
var_dump($form);
$this->coapp_mdl->insert_signature($form, $sig_name);
}
}
I have big problem, I want to read rss feeds from mydealz.de and save their titles, contents and dates to my db. I'm using cakephp, is there any easy way to do it? I'm simply out of ideas
I was trying to do that from this tutorial : http://www.google.com/url?sa=D&q=http://blog.loadsys.com/2009/06/19/cakephp-rss-feed-datasource/&usg=AFQjCNFhFxVyjqEFoPFfZgt-X2NYpmv0OQ but in model I delclared that I'm not using database.
App::import('Core', 'HttpSocket');
$HttpSocket = new HttpSocket();
$input = $HttpSocket->get('http://www.example.com/something.xml');
App::import('Xml');
$xml = new Xml($input);
$xmlAsArray = $xml->toArray();
foreach($xmlAsArray as $item) {
$this->Article->create();
$data['Article'] = array(
'title' => $item['title'],
'contents' => $item['contents'],
'date' => $item['date']
);
$this->Article->save($data);
}