Recipe 15.7.
Reading the ID3 Tag of a Sound File
Problem
You want to access information about the MP3 file
you are playing, such as the name of the song, artist, album,
genre, etc.
Solution
Read the id3 property of the Sound
object.
Discussion
MP3 audio files are able to contain an abundance
of metadata about the sound. This is most often used in music files
to record the name of the song, the artist, album, genre, year of
release, composer, etc. How much information is actually included
in these tags depends on who encoded or tagged the file. In most
cases though, you'll at least be able to get at the songname
and artist tag.
This data is available to you in ActionScript
through the id3 property of a Sound object.
This property is an instance of the flash.media.ID3Info class,
which contains the following properties:
-
album
-
artist
-
comment
-
genre
-
songName
-
TRack
-
year
So, to read the song's name, you would access it
as follows:
_sound.id3.songName
There is just one catch to all of this, though:
you can't access these id3 tags until they have actually
downloaded into your .swf. If you try to read a tag
immediately after you create your Sound object or call
play( ), it won't be
defined. Factually, the request for the sound file has probably not
even reached the server at that point, so of course there will be
no tag data available.
So, how do you know when this id3 data is
available? Fortunately, the Sound object has an ID3
event that you can listen for. When this event fires, it is safe to
read the id3 tags. The Sound class extends the
EventDispatcher class,
so you can use add- EventDispatcher to listen for this
event, which is defined as flash.events.Event.ID3, and
assign a handler method to it; this is the method to use for
reading the id3 tags.
The following example creates a text field and
lists all available id3 tags:
package {
import flash.display.Sprite;
import flash.media.Sound;
import flash.net.URLRequest;
import flash.events.Event;
import flash.text.TextField;
public class ID3Reader extends Sprite {
private var _sound:Sound;
public function ID3Reader ( ) {
_sound = new Sound(new URLRequest("song.mp3"));
_sound.addEventListener(Event.ID3, onID3);
_sound.play( );
}
public function onID3(event:Event):void {
// Create a text field and display it
var id3Display:TextField = new TextField( );
addChild(id3Display);
id3Display.x = 10;
id3Display.y = 20;
id3Display.width = 200;
id3Display.height = 200;
id3Display.background = true;
id3Display.multiline = true;
id3Display.wordWrap = true;
// Add some info about the song to the text field
id3Display.text += _sound.id3.songName + "\n";
id3Display.text += _sound.id3.artist + "\n";
id3Display.text += _sound.id3.album + "\n";
id3Display.text += _sound.id3.year + "\n"; }
}
}
}
See Also
Recipe
15.1 for information on how to load external sound files and Recipe
15.6.
|