Posted By

chrisaiv on 12/08/07


Tagged

mp3 as3 fms2 AMF0


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

THEPWN3R
enajenkins
akashaman
ClayVillage
tspitzr


AS3: Streaming Mp3 Player using Flash Media Server 2


 / Published in: ActionScript 3
 

This is how I was able to achieve a Streaming MP3 player using FMS2. Here are a list of sources that I learned/borrowed from.

http://www.peldi.com/fmswiki/index.php?title=Tutorials http://webmxml.no-ip.info/flextraining/fmsmusic/bin/srcview/index.html http://renaun.com/flex2/posts/mp3app/index.html http://renaun.com/blog/2006/12/01/163/ http://www.adobe.com/devnet/flashmediaserver/articles/ondemandplayer02.html http://maohao.wordpress.com/category/flash-media-server/ http://livedocs.adobe.com/fms/2/docs/wwhelp/wwhimpl/js/html/wwhelp.htm?href=00000128.html http://www.nathanderksen.com/ http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&productId=2&postId=1561

  1. /*******************************
  2. Import Classes
  3. *******************************/
  4. //Allow AS3 to talk to FMS2 AS1
  5. NetConnection.defaultObjectEncoding = ObjectEncoding.AMF0;
  6.  
  7. /*******************************
  8. Var
  9. *******************************/
  10. var rtmp:String = "rtmp://yourserver.com";
  11. var songList:Array = new Array("You and I", "05 Phantom pt. I");
  12. var nc:NetConnection = new NetConnection();
  13. // nc.objectEncoding = flash.net.ObjectEncoding.AMF0;
  14. var ns:NetStream;
  15. var id3_ns:NetStream;
  16. var nsClient:Object = new Object();
  17. var id3Client:Object = new Object();
  18. var isConnected:Boolean = false;
  19. var currentSong:Number = 0;
  20. var soundXForm:SoundTransform = new SoundTransform();
  21. soundXForm.volume = 0.5;
  22.  
  23. /*******************************
  24. Event Listeners
  25. *******************************/
  26. prev_btn.addEventListener(MouseEvent.CLICK, prevHandler);
  27. next_btn.addEventListener(MouseEvent.CLICK, nextHandler);
  28. play_mc.addEventListener(MouseEvent.CLICK, toggleButton);
  29. play_mc.addEventListener(MouseEvent.CLICK, pauseHandler);
  30.  
  31. seekBar_mc.buttonMode = true;
  32. seekBar_mc.addEventListener(MouseEvent.MOUSE_DOWN, seekStartDrag);
  33.  
  34. seekScrub_mc.buttonMode = true;
  35. seekScrub_mc.addEventListener(MouseEvent.MOUSE_DOWN, seekStartDrag);
  36.  
  37. volScrub_mc.buttonMode = true;
  38. volScrub_mc.scaleX = (volBar_mc.scaleX / 2);
  39. volScrub_mc.addEventListener(MouseEvent.MOUSE_DOWN, volStartDrag);
  40.  
  41. volBar_mc.buttonMode = true;
  42. volBar_mc.addEventListener(MouseEvent.MOUSE_DOWN, volStartDrag);
  43.  
  44. /*******************************
  45. Event Handlers
  46. *******************************/
  47. function prevHandler(e:MouseEvent):void {
  48. prevSong();
  49. }
  50. function pauseHandler(e:MouseEvent):void {
  51. pauseSong();
  52. }
  53. function playHandler(e:MouseEvent):void {
  54. //Play the song based on the position of the seekKnob
  55. playSong(ns.time);
  56. }
  57. function nextHandler(e:MouseEvent):void {
  58. nextSong();
  59. }
  60. function toggleButton(e:MouseEvent) {
  61. // trace(e.target.currentFrame);
  62. //on - 1 :: onOver - 5 :: mute - 10 :: muteOver - 15
  63. if (e.target.currentFrame == 1)
  64. {
  65. e.target.gotoAndStop(10);
  66. } else if (e.target.currentFrame == 5)
  67. {
  68. e.target.gotoAndStop(15);
  69. } else if (e.target.currentFrame == 10)
  70. {
  71. e.target.gotoAndStop(1);
  72. } else if (e.target.currentFrame == 15)
  73. {
  74. e.target.gotoAndStop(5);
  75. }
  76. }
  77. /*******************************
  78. Connect to FMS and play song
  79. *******************************/
  80. //This Handles a Function call made by the Flash Media Server default main.asc
  81. NetConnection.prototype.onBWDone = function(info) {}
  82. NetConnection.prototype.onBWCheck = function() {}
  83.  
  84. function createConnection(appURL:String):void {
  85. if( !nc.connected){
  86. nc.connect(appURL);
  87. nc.addEventListener( NetStatusEvent.NET_STATUS, netStatusHandler );
  88. nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
  89. }else{
  90. nc.close();
  91. isConnected = false;
  92. }
  93. }
  94. function securityErrorHandler( e ):void{
  95. trace("SecurityError: " + e);
  96. }
  97. //Detect when a connection has been made as well as the status of a playing song
  98. function netStatusHandler( e:NetStatusEvent ):void {
  99. switch( e.info.code ) {
  100. case "NetConnection.Connect.Success":
  101. connectionSuccess( new Event( "success" ) );
  102. break;
  103. case "NetConnection.Connect.Failed":
  104. connectionFailed( new Event( "failed" ) );
  105. break;
  106. case "NetStream.Play.Stop":
  107. // trace("netStatusHandler:code: " + e.info.code);
  108. break;
  109. default:
  110. //trace( "netStatusHandler:code: " + e.info.code );
  111. break;
  112. }
  113. }
  114. function connectionSuccess( e:Event ):void {
  115. //A. Assign that a NetConnection has been made
  116. isConnected = true;
  117. //B. Assign a new NetStream connection
  118. if( ns == null ){
  119. ns = new NetStream(nc);
  120. ns.addEventListener( AsyncErrorEvent.ASYNC_ERROR, catchAll );
  121. ns.addEventListener( NetStatusEvent.NET_STATUS, netStatusHandler );
  122. ns.addEventListener( IOErrorEvent.IO_ERROR, catchAll );
  123. }
  124. //C. Assign a new ID3 Netstream Connection
  125. if( id3_ns == null ) {
  126. id3_ns = new NetStream(nc);
  127. id3_ns.addEventListener( AsyncErrorEvent.ASYNC_ERROR, catchAll );
  128. id3_ns.addEventListener( IOErrorEvent.IO_ERROR, catchAll );
  129. id3_ns.addEventListener( NetStatusEvent.NET_STATUS, netStatusHandler );
  130. }
  131. playSong(0);
  132. }
  133. function connectionFailed( e:Event ):void {
  134. isConnected = false;
  135. }
  136. function catchAll( e:Event ){
  137. trace("\n\n\n\nCatch All: " + e + "\n\n\n\n");
  138. }
  139.  
  140. /*******************************
  141. Single callback functions that process the information sent by FMS2
  142. *******************************/
  143. nsClient.onPlayStatus = function( obj:Object ):void{
  144. switch ( obj.code ){
  145. case "NetStream.Play.Switch":
  146. break;
  147. case "NetStream.Play.Complete":
  148. soundCompleteHandler();
  149. break;
  150. default:
  151. for( var a:String in obj ){ trace(a + " " + obj[ a ]); }
  152. break;
  153. }
  154. }
  155. id3Client.onId3 = function( obj:Object ):void{
  156. if(obj["artist"] != undefined){
  157. text_txt.text = "Artist: " + obj["artist"].toString();
  158. }
  159. if(obj["songtitle"] != undefined){
  160. text_txt.text += "\nTitle: " + obj["songtitle"].toString()
  161. }
  162. for( var b:String in obj ) {
  163. //trace(b + ": " + obj[ b ]);
  164. }
  165. }
  166. function setNetClientLength(length:Number):void{
  167. nsClient.length = length;
  168. }
  169. /*******************************
  170. Song
  171. *******************************/
  172. function prevSong():void {
  173. //A. Close NetStream connection to allow for a new one
  174. ns.close();
  175. //B. If there is no previous song to play, restart the currentSong
  176. if (currentSong > 0) {
  177. currentSong--;
  178. } else {
  179. currentSong = songList.length - 1;
  180. }
  181. //C. Create a new Net Stream. The new Event is simply Fluff
  182. connectionSuccess( new Event("Empty String"));
  183. }
  184. function nextSong():void {
  185. //A. Close the NetStream connection to allow for a new one
  186. ns.close();
  187. //B. If there is another song in the playlist, play on!
  188. if (currentSong < songList.length - 1) {
  189. currentSong++;
  190. }else {
  191. //C. Otherwise return to the first song on the playlist
  192. currentSong = 0;
  193. }
  194. //D. Create a new NetStream connection
  195. connectionSuccess(new Event("Empty String"));
  196. }
  197. function playSong(position:Number):void {
  198. text_txt.text = "";
  199. //A. Ensure that the connection to FMS is open
  200. if (!isConnected) { createConnection(rtmp); }
  201. //B. Find the ID3 Information of the Mp3
  202. id3_ns.play("id3:" + songList[currentSong]);
  203. //C. Reassign the id3Client:Object to re-catch any ID3 info
  204. id3_ns.client = id3Client;
  205. //C. Play the new NetStream connection
  206. //play(songName, postion in Seconds:Number, duration in seconds:Number, flush:Boolean -> false means play the next song)
  207. ns.play("mp3:" + songList[currentSong], position);
  208. //D. Reassign the nsClient:Object to ensure the catch of the onPlayStatus
  209. ns.client = nsClient;
  210. //E. Adjust the Volume
  211. ns.soundTransform = soundXForm;
  212. //E. Retreive the Length of the Song from FMS and set it to nsClient.length
  213. nc.call("getStreamLength", new Responder(setNetClientLength), "mp3:" + songList[currentSong]);
  214. //F. Begin tracking the position of the song for the status bar
  215. seekBar_mc.addEventListener(Event.ENTER_FRAME, songPosition);
  216. }
  217. function pauseSong():void {
  218. ns.togglePause();
  219. }
  220. function soundCompleteHandler():void {
  221. trace("soundCompleteHandler");
  222. //Garbage Collection
  223. seekBar_mc.removeEventListener(Event.ENTER_FRAME, songPosition);
  224. //This resets the Progress Bar back to 0
  225. songPosition(new Event("Empty String"));
  226. //Flip the Play/Pause button back to play
  227. play_mc.gotoAndStop("play");
  228. //Repeat the song
  229. nextSong();
  230. }
  231. /*******************************
  232. Volume
  233. *******************************/
  234. function volStartDrag(e:MouseEvent):void {
  235. volumeUpdate(e);
  236. volBar_mc.addEventListener(MouseEvent.MOUSE_MOVE, volumeUpdate);
  237. volScrub_mc.addEventListener(MouseEvent.MOUSE_MOVE, volumeUpdate);
  238. stage.addEventListener(MouseEvent.MOUSE_UP, volumeStopDrag);
  239. }
  240. function volumeStopDrag(e:MouseEvent):void {
  241. volBar_mc.removeEventListener(MouseEvent.MOUSE_MOVE, volumeUpdate);
  242. volScrub_mc.removeEventListener(MouseEvent.MOUSE_MOVE, volumeUpdate);
  243. stage.removeEventListener(MouseEvent.MOUSE_UP, volumeStopDrag);
  244. }
  245. function volumeUpdate(e:MouseEvent):void{
  246. //Calculate the Distance Between the Mouse (e.stageX) and the volBar_mc.x
  247. var dist:Number = ((e.stageX - volBar_mc.x) / volBar_mc.width);
  248. if (dist >= 0 && dist <= 1){
  249. //Adjust the Volume Bar GUI
  250. volumeBarUpdate(dist);
  251. //Adjust the Sound Volume
  252. soundXForm.volume = dist;
  253. ns.soundTransform = soundXForm;
  254. }
  255. }
  256. function volumeBarUpdate(dist:Number):void{
  257. volScrub_mc.scaleX = (dist);
  258. }
  259. /*******************************
  260. Seek
  261. *******************************/
  262. function seekStartDrag(e:MouseEvent):void {
  263. //A. Jump to the spot in the song where the user clicked
  264. seekUpdate(e);
  265. //A. Remain seeking while the Mouse is Still Down and Moving
  266. seekBar_mc.addEventListener(MouseEvent.MOUSE_MOVE, seekUpdate);
  267. seekScrub_mc.addEventListener(MouseEvent.MOUSE_MOVE, seekUpdate);
  268. //C. Self Destruct
  269. stage.addEventListener(MouseEvent.MOUSE_UP, seekStopDrag);
  270. }
  271. function seekStopDrag(e:Event):void {
  272. seekScrub_mc.removeEventListener(MouseEvent.MOUSE_MOVE, seekUpdate);
  273. seekBar_mc.removeEventListener(MouseEvent.MOUSE_MOVE, seekUpdate);
  274. stage.removeEventListener(MouseEvent.MOUSE_UP, seekStopDrag);
  275. }
  276. function seekUpdate(e:MouseEvent):void {
  277. //A. If a user clicks a new part of the song, you must first seek() then update the Progress Bar
  278. var dist:Number = ((e.stageX - seekBar_mc.x) / seekBar_mc.width);
  279. //B. Seek the spot
  280. ns.seek(Math.floor(nsClient.length * dist));
  281. //C. Upate the Progress Bar
  282. seekBarUpdate(dist)
  283. }
  284. function songPosition(e:Event):void{
  285. var dist:Number = ns.time / nsClient.length;
  286. if (!isNaN(dist)) {
  287. seekBarUpdate(dist);
  288. } else {
  289. seekBarUpdate(0);
  290. }
  291. }
  292. function seekBarUpdate(dist:Number){
  293. //A. Adjust the GUI
  294. seekScrub_mc.scaleX = dist;
  295. }
  296. /*******************************
  297. Launch the Application on Frame(0)
  298. *******************************/
  299. addFrameScript(0, createConnection(rtmp));

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: jinpingv on April 8, 2008

That's just what I'm looking for. Thank you!

Posted By: jinpingv on April 8, 2008

That's just what I'm looking for. Thank you!

Posted By: Roshambo on July 18, 2008

You made my day with this. Thanks so much!

Posted By: Emilio on January 27, 2009

One question, is posible to connect with these snippet a radio station

Posted By: chrisaiv on February 3, 2009

Hey Emilio, Care to elaborate?

Posted By: perumal123 on July 14, 2009

How do create fms audio player asc files??

You need to login to post a comment.