Thursday, 10 September 2009

Create a Simple and Attractive MP3 Player

Getting started

First I'll just go through what we need to complete this tutorial:

I've used the 3rd party class Caurina Tweener to tween elements on the screen. This is not required because you can use Flash's own tween class to do the same job. Mind you, if you're not familiar with Caurina I suggest you to take a look. Tween Lite is another 3rd party tweener you might have heard of. It's a very powerful tween class which you could also use for this project if you wanted. You can find Caurina Tweener in the source code.

  • The source code includes one mp3 file that we'll need: Tarzan's mighty yell :). You can also use your own mp3 if you like.
  • Also in the source code you'll find the directory "ai" which contains the simplemp3player.ai file. This file includes all the graphics for the player.
  • Lastly I've included font that we need. It's called 04b03 and it's a bitmap font. Install it and you're ready to go.

Step 1: Create New File

First you need to create a new Flash Actionscript 3.0 document. You don't need to adjust any document properties.

Go to Flash > Preferences > AI file importer on Mac or Edit > Preferences > AI file importer on Windows. Make sure you have the following settings:

Save it and give it the name "SimpleMP3Player.fla". Also copy the directory "caurina" and "tarzan.mp3" to same place as your .fla file.

Step 2: Import Illustrator File

Now we're ready to import the Illustrator file. Go to File > Import > Import to Stage. Locate "simplemp3player.ai" from the source package "ai" directory, press OK and you'll get the screen as shown below. Set the Convert to layers "Flash layers" so you get all the layers contained within the ai file directly to Flash. The next two options, as shown in the image, place all the artwork to same coordinates as in ai file and resize your Flash document exactly to size that we need.

When you click OK in the import dialog your document should look like the image shown above.

Step 3: Create the Button Sprite

You probably noticed play and pause buttons in the last image. Those are going to be our button sprite that controls the sound. All the buttons are grouped into one group.

Select only buttons group and press F8 to get the "Convert to symbol" screen. Give it the name "buttons" and make sure you've selected MovieClip as the type. Set the registration to the top left corner and click OK. Switch to the Properties panel and give the object a instance name "buttons". The image below illustrates these steps visually:

We have our buttons in one movieclip, but the mask is not included. We need one more movieclip to bind them all together.

Select the buttons movieclip and the mask object. Again press F8 and now give it a name of "buttonSprite". Also remember to give it a instance name. This time "bs" (I know what you're thinking, but this is an abbreviation of ButtonSprite).

Step 4: Manual Masking

Now our button sprite is almost ready to rock. All we need to do is mask it so that it shows just one button at a time.

Double-click your buttonSprite movieclip. Create a new layer above the active layer and name it "mask". Select the mask object and cut it using "Cmd + X" on Mac or "Ctrl + X" on Windows. Select the mask layer and paste using "Cmd + V" on Mac or "Ctrl + V" on Windows. It doesn't matter where your mask object is because next we align it to right place.

With your mask still selected open up the Align panel(Window > Align) and make sure the "To stage" button is pressed down. Now press the "Align top edge" and "Align left edge" buttons and your mask object should now be in the correct position, the top left corner of your movieclip.

The only thing remaining to do is mask the buttons. Right-click above the mask layer and choose Mask.

You can see the effect instantly; only one button is visible.

Step 5: Start Creating the Display

Let's forget the buttons for a while and focus on the MP3 player's display. I'll show you how to build this display element manually. It could be done with AS3, of course, but let's do it manually this time.

First select the mask element from mask layer. Convert it to a movieclip and give it the name "displayMask". Use this name as the instance name too. The mask for display is ready, so hide the layer. Next, create a layer between the buttons layer and the mask layer. Name it "text". Select the Text tool from the Tools palette and use the options shown in the image below:

Step 6: Add Textfields to Display

We need textfields to show our information (artist, song name, loading percentage and song length). We'll create textfields manually to the stage.

First draw textfieds on the text layer as shown in the image below. Convert all three textfields in to one single movieclip called "playerTexts". Create one more textfield and call it "preloader". You don't need to convert this to a movieclip.

Step 7: Complete the Display

All we need to do is include our new loader-textfield and playerTexts-movieclip in one movieclip so we can control texts as and when we like.

Select the loader-textfield and playerTexts-movieclip and press F8. Give it a name and an instance name of "display". Now we've completed our display hierarchy, it should look like this:

To write a data example to songInfo-textfield we have to write the following line of code:

  1. display.playerTexts.songInfo.text = 'This is where we put the artist and song name';

So now we have every graphical element ready that we need for the MP3 Player. Next we'll jump deep into the code, so dive with me!

Step 8: Create Document Class File

To get the code to work we need to create the document class. Document class code is executed first when .swf files play. You don't need to write your code to the timeline anymore and your class is easier to import to another .fla file in the future if it's needed.

Go to File > New. Select "Actionscript file" from the window which opens and click OK. Save the file to the same folder as your .fla file and name it "SimpleMP3Player.as".

Now assign your new .as file as document class. Click the stage and go to the Properties panel. There you'll find the "Class" field where you need to enter the class name you've created. Enter "SimpleMP3Player" and click the small pencil button. If you spelled the class name correctly the "SimpleMP3Player.as" file should become active. Otherwise Flash will throw an error.

Step 9: The Code

Code brings everything to life. Here's the completed ActionScript, I'll explain it block by block. Check also the source code from the source package, I've commented it from beginning to end.

  1. package
  2. {
  3. import flash.display.MovieClip;
  4. import flash.events.Event;
  5. import flash.events.EventDispatcher;
  6. import flash.events.IOErrorEvent;
  7. import flash.events.MouseEvent;
  8. import flash.events.ProgressEvent;
  9. import flash.events.TimerEvent;
  10. import flash.media.Sound;
  11. import flash.media.SoundChannel;
  12. import flash.media.ID3Info;
  13. import flash.net.URLRequest;
  14. import flash.utils.Timer;
  15. import flash.text.TextField;
  16. import flash.text.TextFieldAutoSize;
  17. import caurina.transitions.Tweener;

  18. public class SimpleMP3Player extends MovieClip
  19. {
  20. // Create some variables that we need
  21. private var mp3File:Sound;
  22. private var mp3FilePosition:SoundChannel;
  23. private var id3Data:ID3Info;
  24. private var id3InfoAvailable = false;

  25. private var updateTime:Timer;

  26. private var playingSound:Boolean = false;
  27. private var soundPosition:Number;
  28. private var songReachedEnd:Boolean = false;

  29. private var buttonPos:Array = new Array('0', '-36', '-72', '-108', '-144', '-180', '-216', '-252');

  30. public function SimpleMP3Player()
  31. {
  32. display.playerTexts.x = -73;
  33. display.mask = displayMask;

  34. bs.buttons.buttonMode = bs.buttons.enabled = false;
  35. bs.buttons.y = buttonPos[3];

  36. loadMP3();
  37. }

  38. private function loadMP3():void
  39. {
  40. mp3File = new Sound();
  41. mp3File.addEventListener(ProgressEvent.PROGRESS, mp3FileLoading);
  42. mp3File.addEventListener(Event.COMPLETE, mp3FileLoaded);
  43. mp3File.addEventListener(IOErrorEvent.IO_ERROR, errorLoadingSound);

  44. mp3File.addEventListener(Event.ID3, getID3Data);
  45. mp3File.load(new URLRequest('tarzan.mp3'));

  46. Tweener.addTween(display.preloader, {x: 96, time:1});
  47. }

  48. private function mp3FileLoading(e:ProgressEvent):void
  49. {
  50. var currentPercent:Number = Math.round(e.bytesLoaded / e.bytesTotal * 100);
  51. display.preloader.text = 'LOADING...' + currentPercent + '%';

  52. if (currentPercent > 50 && id3InfoAvailable)
  53. {
  54. Tweener.addTween(display.preloader, {x: 200, time:1, onComplete:playMP3, onCompleteParams:[false, 0]});
  55. mp3File.removeEventListener(ProgressEvent.PROGRESS, mp3FileLoading);
  56. }
  57. }

  58. private function mp3FileLoaded(e:Event):void
  59. {
  60. mp3File.removeEventListener(Event.COMPLETE, mp3FileLoaded);
  61. mp3File.removeEventListener(ProgressEvent.PROGRESS, updateBufferField);
  62. Tweener.addTween(display.playerTexts.buffer, {x: 200, time:1});
  63. }

  64. private function errorLoadingSound(e:IOErrorEvent):void
  65. {
  66. trace('Error loading sound: ' + e);
  67. }

  68. private function getID3Data(e:Event):void
  69. {
  70. id3InfoAvailable = true;
  71. id3Data = mp3File.id3;
  72. }

  73. private function playMP3(useSp:Boolean, sp:Number):void
  74. {
  75. if (useSp) mp3FilePosition = mp3File.play(sp);
  76. else mp3FilePosition = mp3File.play();

  77. playingSound = true;
  78. mp3FilePosition.addEventListener(Event.SOUND_COMPLETE, songFinished);
  79. mp3File.addEventListener(ProgressEvent.PROGRESS, updateBufferField);

  80. bs.buttons.buttonMode = bs.buttons.enabled = true;
  81. bs.buttons.y = buttonPos[0];

  82. bs.buttons.addEventListener(MouseEvent.MOUSE_OVER, mouseOverBs);
  83. bs.buttons.addEventListener(MouseEvent.MOUSE_OUT, mouseOutBs);
  84. bs.buttons.addEventListener(MouseEvent.CLICK, mouseClickBs);

  85. updateTime = new Timer(100);
  86. updateTime.addEventListener(TimerEvent.TIMER, getMP3Time);
  87. updateTime.start();

  88. var si:String = id3Data.artist + ' - ' + id3Data.songName;
  89. si = si.toUpperCase();
  90. display.playerTexts.songInfo.autoSize = TextFieldAutoSize.LEFT;
  91. display.playerTexts.songInfo.wordWrap = false;
  92. display.playerTexts.songInfo.text = si;

  93. Tweener.addTween(display.playerTexts, {x: 60, time:1});
  94. }

  95. private function updateBufferField(e:ProgressEvent):void
  96. {
  97. var currentPercent:Number = Math.round(e.bytesLoaded / e.bytesTotal * 100);
  98. display.playerTexts.buffer.text = currentPercent + '%';
  99. }

  100. private function getMP3Time(e:TimerEvent):void
  101. {
  102. var totalMinutes = Math.floor(mp3File.length / 1000 / 60);
  103. var totalSeconds = Math.floor(mp3File.length / 1000) % 60;
  104. var currentMinutes = Math.floor(mp3FilePosition.position / 1000 / 60);
  105. var currentSeconds = Math.floor(mp3FilePosition.position / 1000) % 60;

  106. if (totalSeconds < totalseconds =" if (currentSeconds < currentseconds ="
  107. display.playerTexts.times.text = currentMinutes + ':' + currentSeconds + '/' + totalMinutes + ':' + totalSeconds;
  108. }

  109. private function songFinished(e:Event):void
  110. {
  111. mp3FilePosition.removeEventListener(Event.SOUND_COMPLETE, songFinished);
  112. updateTime.removeEventListener(TimerEvent.TIMER, getMP3Time);

  113. bs.buttons.y = buttonPos[3];
  114. mp3FilePosition.stop();

  115. playingSound = false;
  116. songReachedEnd = true;

  117. soundPosition = 0;
  118. display.playerTexts.times.text = 'PLAY AGAIN?';
  119. }

  120. /*
  121. * allButtons.bs event methods begin
  122. */

  123. private function mouseOverBs(e:MouseEvent):void
  124. {
  125. if (playingSound) bs.buttons.y = buttonPos[5];
  126. else bs.buttons.y = buttonPos[1];

  127. if (songReachedEnd && !playingSound) bs.buttons.y = buttonPos[1];
  128. }

  129. private function mouseOutBs(e:MouseEvent):void
  130. {
  131. if (playingSound) bs.buttons.y = buttonPos[0];
  132. else bs.buttons.y = buttonPos[4];

  133. if (songReachedEnd && !playingSound) bs.buttons.y = buttonPos[3];
  134. }

  135. private function mouseClickBs(e:MouseEvent):void
  136. {
  137. if (playingSound)
  138. {
  139. bs.buttons.y = buttonPos[4];
  140. soundPosition = mp3FilePosition.position;
  141. updateTime.stop();
  142. mp3FilePosition.stop();
  143. playingSound = false;
  144. display.playerTexts.times.text = 'PAUSE';
  145. }
  146. else if (!playingSound)
  147. {
  148. bs.buttons.y = buttonPos[2];
  149. playMP3(true, soundPosition);
  150. playingSound = true;

  151. }
  152. else if (songReachedEnd)
  153. {
  154. songReachedEnd = false;
  155. playMP3(false, 0);
  156. }
  157. }
  158. }
  159. }

0 nhận xét:

Post a Comment

 

Blogroll

Site Info

Text

Tut - Designer Copyright © 2009 WoodMag is Designed by Ipietoon for Free Blogger Template