Leer y editar etiquetas ID3v1 e ID3v2 con CakePHP 1.2

Reading time ~20 minutes

Si, como yo, estáis interesados en editar y leer las etiquetas ID3 de los ficheros mp3 que se suban a vuestro servidor, podéis hacerlo utilizando las funciones propias de PHP para ello (necesitáis que vuestro hosting lo tenga instalado) o bien, si os pasa igual que a mi que en mi hosting no tienen habilitadas estas funciones (y si no tienes un servidor dedicado no te las instalarán para no detener el servicio), podéis utilizar las classes de PHP GetID3.

Si no la conocíais os recomiendo que la descarguéis y hagáis alguna prueba con ella, realmente se le puede sacar mucho jugo ya que con ella no sólo podemos editar etiquetas ID3; esto son algunos de los muchos formatos cuya información podéis consultar y / o editar con este magnífico conjunto de clases:

getID3() is a PHP script that extracts useful information from MP3s & other multimedia file formats:

He eliminado unos cuantos formatos de la lista, si queréis verlos todos id a su página web.

¡Al grano! Ya conocemos las clases ID3 (aunque sea un poco por encima, como yo..) y queremos implementarlas en nuestra aplicación de Cake.

No es muy complicado si utilizamos las demos que nos dan en el zip que nos descargamos de getID3.org. Simplemente debemos tener en cuenta que los “require” que utilicen en las demos debemos substituirlas por App::import(‘vendor’,’rutadelaclase’).

Lo primero que deberemos hacer será descargar getID3. Si queréis editar etiquetas ID3v2 deberéis descargar la versión estable (actualmente la 1.7.9) ya que en la versión beta (actualmente la 2.0.0-b5) no funcionan las clases necesarias.

Una vez descargado, lo descomprimimos y lo subimos a la carpeta vendors de nuestro proyecto Cake (para mayor comodidad renombrar la carpeta a “getid3”). Seguramente habréis visto que existen dos carpetas vendor en vuestra aplicación de Cake. Debéis ponerlo en la que se encuentra en la carpeta raíz (junto con las carpeta “app” y “cake”).

Ahora que ya tenemos nuestro plugin en la aplicación debemos crear un componente que nos sirva de conexión entre las librerías getID3 y nuestro Cake.

Para hacerlo utilizaremos como referencia las demos “demo.basic.php” y “demo.simple.write.php”. Recordad que hay que substituir los require e includes por App::import(). Este es el resultado que he obtenido yo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
class Getid3Component extends Object
{
  function __construct() {
    set_time_limit(20 * 3600);
    ignore_user_abort(false);
  }

  function extract($filename) {
    // Importamos el fichero getid3.php que contiene la classe getID3
    App::import('vendor', 'getid3/getid3', array('file' => 'getid3.php'));
    // Initialize getID3 engine
    $getID3 = new getID3;

    // Analyze file and store returned data in $ThisFileInfo
    $ThisFileInfo = $getID3->analyze($filename);
    // Devolvemos un array con toda la información del fichero
    return $ThisFileInfo;
  }

  function write($filename, $data)
  {
    App::import('vendor', 'getid3/getid3/getid3');

    // Initialize getID3 engine
    $getID3 = new getID3;
    // Indicamos a getID3 que utilice la codificación de Cake
    $getID3->setOption(array('encoding' => Configure::read('App.encoding')));

    App::import('vendor', 'getid3/getid3', array('file' => 'write.php'));

    // Initialize getID3 tag-writing module
    $tagwriter = new getid3_writetags;

    $tagwriter->filename       = $filename;
    $tagwriter->tagformats     = array('id3v1', 'id3v2.3');

    // set various options (optional)
    $tagwriter->overwrite_tags = true;
    $tagwriter->tag_encoding   = Configure::read('App.encoding');
    $tagwriter->remove_other_tags = true;

    // populate data array
    $TagData['title'][]   = $data['title'];
    $TagData['artist'][]  = $data['artist'];
    $TagData['album'][]   = $data['album'];
    $TagData['year'][]    = $data['year'];
    $TagData['genre'][]   = $data['genre'];
    $TagData['comment'][] = $data['comment'];
    $TagData['track'][]   = $data['track'];

    $tagwriter->tag_data = $TagData;

    // write tags
    if ($tagwriter->WriteTags()) {
      if (!empty($tagwriter->warnings)) {
        return $tagwriter->warnings;
      }
      return true;
    } else {
      return $tagwriter->errors;
    }
  }
}

Recordad que los componentes van en la carpeta app/controllers/components y que el nombre de este fichero deberá ser getid3.php.

Ahora que ya tenemos nuestro componente vayamos al controlador sobre el que queramos utilizarlo y añadamoslo al resto de componentes:

1
2
3
4
5
6
7
<?php
class AudiosController extends AppController
{
  var $name = 'Audios';
  var $components = array('Upload', 'Getid3');
  // [...]
}

Y sólo nos queda saber cómo utilizarlo:

1
2
3
4
5
6
7
8
9
$datos = array(
  'album' => 'Nombre del álbum',
  'title' => 'Título del tema',
  'artist' => 'Artista',
  'year' => 'Año',
  'genre' => 'Estilo',
  'comment' => 'Comentario'
);
$this->Getid2->write('rutadelfichero.mp3', $datos);

Y para leer los datos de un mp3:

1
$this->Getid2->extract('rutadelfichero.mp3')

Que nos dará una salida similar a ésta.

Habéis visto más o menos el método de implementar funciones de getID3 en CakePHP. Ahora es tarea vuestra intentar añadir más funcionalidades a vuestro complemento según vuestras necesidades.

Como siempre, espero que le sirva a alguien!

Páginas de referencia:

Salida de mi fichero de prueba mp3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
Array
(
    [GETID3_VERSION] => 1.7.9-20090308
    [filesize] => 263776
    [avdataoffset] => 4096
    [avdataend] => 263648
    [fileformat] => mp3
    [audio] => Array
        (
            [dataformat] => mp3
            [channels] => 2
            [sample_rate] => 44100
            [bitrate] => 128000
            [channelmode] => stereo
            [bitrate_mode] => cbr
            [lossless] =>
            [encoder_options] => CBR128
            [compression_ratio] => 0.0907029478458
            [streams] => Array
                (
                    [0] => Array
                        (
                            [dataformat] => mp3
                            [channels] => 2
                            [sample_rate] => 44100
                            [bitrate] => 128000
                            [channelmode] => stereo
                            [bitrate_mode] => cbr
                            [lossless] =>
                            [encoder_options] => CBR128
                            [compression_ratio] => 0.0907029478458
                        )

                )

        )

    [tags] => Array
        (
            [id3v1] => Array
                (
                    [title] => Array
                        (
                            [0] => Títol del tema
                        )

                    [artist] => Array
                        (
                            [0] => Jo mateix
                        )

                    [album] => Array
                        (
                            [0] => Muahahahahah
                        )

                    [year] => Array
                        (
                            [0] => 2009
                        )

                    [comment] => Array
                        (
                            [0] => from www.underave.net
                        )

                    [genre] => Array
                        (
                            [0] => Techno
                        )

                )

            [id3v2] => Array
                (
                    [title] => Array
                        (
                            [0] => Títol del tema
                        )

                    [artist] => Array
                        (
                            [0] => Jo mateix
                        )

                    [album] => Array
                        (
                            [0] => Muahahahahah
                        )

                    [year] => Array
                        (
                            [0] => 2009
                        )

                    [genre] => Array
                        (
                            [0] => Techno
                        )

                    [comments] => Array
                        (
                            [0] => from www.underave.net
                        )

                )

        )

    [encoding] => ISO-8859-1
    [filename] => Bong0.mp3
    [filepath] => /public_html/waste/v3.2/app/webroot/files/mp3
    [filenamepath] => /public_html/waste/v3.2/app/webroot/files/mp3/Bong0.mp3
    [id3v2] => Array
        (
            [header] => 1
            [flags] => Array
                (
                    [unsynch] =>
                    [exthead] =>
                    [experim] =>
                )

            [majorversion] => 3
            [minorversion] => 0
            [headerlength] => 4096
            [tag_offset_start] => 0
            [tag_offset_end] => 4096
            [encoding] => UTF-8
            [comments] => Array
                (
                    [title] => Array
                        (
                            [0] => Títol del tema
                        )

                    [artist] => Array
                        (
                            [0] => Jo mateix
                        )

                    [album] => Array
                        (
                            [0] => Muahahahahah
                        )

                    [year] => Array
                        (
                            [0] => 2009
                        )

                    [genre] => Array
                        (
                            [0] => Techno
                        )

                    [comments] => Array
                        (
                            [0] => from www.underave.net
                        )

                )

            [TIT2] => Array
                (
                    [0] => Array
                        (
                            [frame_name] => TIT2
                            [frame_flags_raw] => 0
                            [data] => ��T���t�o�l� �d�e�l� �t�e�m�a�
                            [datalength] => 31
                            [dataoffset] => 10
                            [framenamelong] => Title/songname/content description
                            [framenameshort] => title
                            [flags] => Array
                                (
                                    [TagAlterPreservation] =>
                                    [FileAlterPreservation] =>
                                    [ReadOnly] =>
                                    [compression] =>
                                    [Encryption] =>
                                    [GroupingIdentity] =>
                                )

                            [encodingid] => 1
                            [encoding] => UTF-16
                        )

                )

            [TPE1] => Array
                (
                    [0] => Array
                        (
                            [frame_name] => TPE1
                            [frame_flags_raw] => 0
                            [data] => ��J�o� �m�a�t�e�i�x�
                            [datalength] => 21
                            [dataoffset] => 51
                            [framenamelong] => Lead performer(s)/Soloist(s)
                            [framenameshort] => artist
                            [flags] => Array
                                (
                                    [TagAlterPreservation] =>
                                    [FileAlterPreservation] =>
                                    [ReadOnly] =>
                                    [compression] =>
                                    [Encryption] =>
                                    [GroupingIdentity] =>
                                )

                            [encodingid] => 1
                            [encoding] => UTF-16
                        )

                )

            [TALB] => Array
                (
                    [0] => Array
                        (
                            [frame_name] => TALB
                            [frame_flags_raw] => 0
                            [data] => ��M�u�a�h�a�h�a�h�a�h�a�h�
                            [datalength] => 27
                            [dataoffset] => 82
                            [framenamelong] => Album/Movie/Show title
                            [framenameshort] => album
                            [flags] => Array
                                (
                                    [TagAlterPreservation] =>
                                    [FileAlterPreservation] =>
                                    [ReadOnly] =>
                                    [compression] =>
                                    [Encryption] =>
                                    [GroupingIdentity] =>
                                )

                            [encodingid] => 1
                            [encoding] => UTF-16
                        )

                )

            [TYER] => Array
                (
                    [0] => Array
                        (
                            [frame_name] => TYER
                            [frame_flags_raw] => 0
                            [data] => ��2�0�0�9�
                            [datalength] => 11
                            [dataoffset] => 119
                            [framenamelong] => Year
                            [framenameshort] => year
                            [flags] => Array
                                (
                                    [TagAlterPreservation] =>
                                    [FileAlterPreservation] =>
                                    [ReadOnly] =>
                                    [compression] =>
                                    [Encryption] =>
                                    [GroupingIdentity] =>
                                )

                            [encodingid] => 1
                            [encoding] => UTF-16
                        )

                )

            [TCON] => Array
                (
                    [0] => Array
                        (
                            [frame_name] => TCON
                            [frame_flags_raw] => 0
                            [data] => ��T�e�c�h�n�o�
                            [datalength] => 15
                            [dataoffset] => 140
                            [framenamelong] => Content type
                            [framenameshort] => genre
                            [flags] => Array
                                (
                                    [TagAlterPreservation] =>
                                    [FileAlterPreservation] =>
                                    [ReadOnly] =>
                                    [compression] =>
                                    [Encryption] =>
                                    [GroupingIdentity] =>
                                )

                            [encodingid] => 1
                            [encoding] => UTF-16
                        )

                )

            [COMM] => Array
                (
                    [0] => Array
                        (
                            [frame_name] => COMM
                            [frame_flags_raw] => 0
                            [data] => ��f�r�o�m� �w�w�w�.�u�n�d�e�r�a�v�e�.�n�e�t�
                            [datalength] => 50
                            [dataoffset] => 165
                            [framenamelong] => Comments
                            [framenameshort] => comments
                            [flags] => Array
                                (
                                    [TagAlterPreservation] =>
                                    [FileAlterPreservation] =>
                                    [ReadOnly] =>
                                    [compression] =>
                                    [Encryption] =>
                                    [GroupingIdentity] =>
                                )

                            [encodingid] => 1
                            [encoding] => UTF-16
                            [language] => eng
                            [languagename] => English
                            [description] =>
                        )

                )

            [TRCK] => Array
                (
                    [0] => Array
                        (
                            [frame_name] => TRCK
                            [frame_flags_raw] => 0
                            [data] =>
                            [datalength] => 1
                            [dataoffset] => 225
                            [framenamelong] => Track number/Position in set
                            [framenameshort] => track_number
                            [flags] => Array
                                (
                                    [TagAlterPreservation] =>
                                    [FileAlterPreservation] =>
                                    [ReadOnly] =>
                                    [compression] =>
                                    [Encryption] =>
                                    [GroupingIdentity] =>
                                )

                            [encodingid] => 1
                            [encoding] => UTF-16
                        )

                )

            [padding] => Array
                (
                    [start] => 236
                    [length] => 3860
                    [valid] => 1
                )

        )

    [id3v1] => Array
        (
            [title] => Títol del tema
            [artist] => Jo mateix
            [album] => Muahahahahah
            [year] => 2009
            [comment] => from www.underave.net
            [genre] => Techno
            [comments] => Array
                (
                    [title] => Array
                        (
                            [0] => Títol del tema
                        )

                    [artist] => Array
                        (
                            [0] => Jo mateix
                        )

                    [album] => Array
                        (
                            [0] => Muahahahahah
                        )

                    [year] => Array
                        (
                            [0] => 2009
                        )

                    [comment] => Array
                        (
                            [0] => from www.underave.net
                        )

                    [genre] => Array
                        (
                            [0] => Techno
                        )

                )

            [padding_valid] => 1
            [tag_offset_end] => 263776
            [tag_offset_start] => 263648
            [encoding] => ISO-8859-1
        )

    [mime_type] => audio/mpeg
    [mpeg] => Array
        (
            [audio] => Array
                (
                    [raw] => Array
                        (
                            [synch] => 4094
                            [version] => 3
                            [layer] => 1
                            [protection] => 0
                            [bitrate] => 9
                            [sample_rate] => 0
                            [padding] => 0
                            [private] => 0
                            [channelmode] => 0
                            [modeextension] => 0
                            [copyright] => 0
                            [original] => 1
                            [emphasis] => 0
                        )

                    [version] => 1
                    [layer] => 3
                    [channelmode] => stereo
                    [channels] => 2
                    [sample_rate] => 44100
                    [protection] => 1
                    [private] =>
                    [modeextension] =>
                    [copyright] =>
                    [original] => 1
                    [emphasis] => none
                    [crc] => 54304
                    [padding] =>
                    [bitrate] => 128000
                    [framelength] => 417
                    [bitrate_mode] => cbr
                )

        )

    [playtime_seconds] => 16.222
    [tags_html] => Array
        (
            [id3v1] => Array
                (
                    [title] => Array
                        (
                            [0] => T&amp;iacute;tol del tema
                        )

                    [artist] => Array
                        (
                            [0] => Jo mateix
                        )

                    [album] => Array
                        (
                            [0] => Muahahahahah
                        )

                    [year] => Array
                        (
                            [0] => 2009
                        )

                    [comment] => Array
                        (
                            [0] => from www.underave.net
                        )

                    [genre] => Array
                        (
                            [0] => Techno
                        )

                )

            [id3v2] => Array
                (
                    [title] => Array
                        (
                            [0] => T&amp;#237;tol del tema
                        )

                    [artist] => Array
                        (
                            [0] => Jo mateix
                        )

                    [album] => Array
                        (
                            [0] => Muahahahahah
                        )

                    [year] => Array
                        (
                            [0] => 2009
                        )

                    [genre] => Array
                        (
                            [0] => Techno
                        )

                    [comments] => Array
                        (
                            [0] => from www.underave.net
                        )

                )

        )

    [bitrate] => 128000
    [playtime_string] => 0:16
)