Sunday, January 10, 2010

Read ID3 Tag of an mp3 File using ActionScript 3.0

ID3 tags are embedded within an mp3 file that stores the metadata. It contains various information such as the title, artist, album, track number, and other information about the file.
Here we will see how to read those information using ActionScript 3.0 and Flex Builder 3.0 as the IDE.
Source:
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.media.Sound;
import flash.net.URLRequest;
import flash.text.TextField;

public class ID3Tag extends Sprite {
private var _sound:Sound;

public function ID3Tag()
{
_sound = new Sound();
var _soundURL:URLRequest = new URLRequest("sound/4one-Surrealism.mp3");
_sound.load(_soundURL);
_sound.addEventListener(Event.ID3, readID3);
}

private function readID3(event:Event):void
{
var tf:TextField = new TextField();
stage.addChild(tf);
tf.appendText("\nArtist: "+_sound.id3.artist);
tf.appendText("\nAlbum: "+_sound.id3.album);
}
}
}

Now I shall explain the above.
The folder organisation is as below.
public function ID3Tag()
{
_sound = new Sound();
var _soundURL:URLRequest = new URLRequest("sound/4one-Surrealism.mp3");
_sound.load(_soundURL);
_sound.addEventListener(Event.ID3, readID3);
}
ID3Tag() is the constructor. We need to load the mp3 which is inside the sound folder. URLRequest is used to point to the file which inturn is loaded using the load method.
We now add an eventlistener which listens to Event.ID3. What this does is if there is an ID3 tag present for the loaded mp3 file, then the corresponding readID3 function will be called.
private function readID3(event:Event):void
{
var tf:TextField = new TextField();
stage.addChild(tf);
tf.appendText("\nAlbum: "+_sound.id3.album);
tf.appendText("\nArtist: "+_sound.id3.artist);
}
We create an new TextField tf which is added to the stage. tf.appendText() method is used to display the tags. _sound.id3 is the method that parses the ID3 tag for us. And the _sound.id3 method contains various properties like album, artist, comment, genre etc. The _sound.id3.album will show the name of the album and likewise.

An updated version of this tutorial can be found at Kirupa.com