groups

info


tags: wordpress

Link to this snippet:


Download to Code Collector

language: PHP
licence: BSD

AS3: STREAMING MP3 PLAYER USING FLASH MEDIA SERVER 2

options: send to code collectorview all maeghan's snippets

AS3: STREAMING MP3 PLAYER USING FLASH MEDIA SERVER 2

//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

/*******************************
Import Classes
*******************************/
//Allow AS3 to talk to FMS2 AS1
NetConnection.defaultObjectEncoding = ObjectEncoding.AMF0;
 
/*******************************
Var
*******************************/
var rtmp:String = "rtmp://yourserver.com";
var songList:Array = new Array("You and I", "05 Phantom pt. I");
var nc:NetConnection = new NetConnection();
//	nc.objectEncoding = flash.net.ObjectEncoding.AMF0;
var ns:NetStream;
var id3_ns:NetStream;
var nsClient:Object = new Object();
var id3Client:Object = new Object();
var isConnected:Boolean = false;
var currentSong:Number = 0;
var soundXForm:SoundTransform = new SoundTransform();
	soundXForm.volume = 0.5;
 
/*******************************
Event Listeners
*******************************/
prev_btn.addEventListener(MouseEvent.CLICK, prevHandler);
next_btn.addEventListener(MouseEvent.CLICK, nextHandler);
play_mc.addEventListener(MouseEvent.CLICK, toggleButton);
play_mc.addEventListener(MouseEvent.CLICK, pauseHandler);
 
seekBar_mc.buttonMode = true;
seekBar_mc.addEventListener(MouseEvent.MOUSE_DOWN, seekStartDrag);
 
seekScrub_mc.buttonMode = true;
seekScrub_mc.addEventListener(MouseEvent.MOUSE_DOWN, seekStartDrag);
 
volScrub_mc.buttonMode = true;
volScrub_mc.scaleX = (volBar_mc.scaleX / 2);
volScrub_mc.addEventListener(MouseEvent.MOUSE_DOWN, volStartDrag);
 
volBar_mc.buttonMode = true;
volBar_mc.addEventListener(MouseEvent.MOUSE_DOWN, volStartDrag);
 
/*******************************
Event Handlers
*******************************/
function prevHandler(e:MouseEvent):void {
	prevSong();
}
function pauseHandler(e:MouseEvent):void {
	pauseSong();
}
function playHandler(e:MouseEvent):void {
	//Play the song based on the position of the seekKnob
	playSong(ns.time);
}
function nextHandler(e:MouseEvent):void {
	nextSong();
}
function toggleButton(e:MouseEvent) {
//	trace(e.target.currentFrame);
	//on - 1 :: onOver - 5 :: mute - 10 :: muteOver - 15
	if (e.target.currentFrame == 1)
	{
		e.target.gotoAndStop(10);
	} else if (e.target.currentFrame == 5)
	{
		e.target.gotoAndStop(15);
	} else if (e.target.currentFrame == 10)
	{
		e.target.gotoAndStop(1);
	} else if (e.target.currentFrame == 15)
	{
		e.target.gotoAndStop(5);
	}
}
/*******************************
Connect to FMS and play song
*******************************/
//This Handles a Function call made by the Flash Media Server default main.asc
NetConnection.prototype.onBWDone = function(info) {}
NetConnection.prototype.onBWCheck = function() {}
 
function createConnection(appURL:String):void {
	if( !nc.connected){
		nc.connect(appURL);
		nc.addEventListener( NetStatusEvent.NET_STATUS, netStatusHandler ); 
		nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
	}else{
		nc.close();
		isConnected = false;
	}
}
function securityErrorHandler( e ):void{
	trace("SecurityError: " + e);
}
//Detect when a connection has been made as well as the status of a playing song
function netStatusHandler( e:NetStatusEvent ):void {
    switch( e.info.code ) {
        case "NetConnection.Connect.Success":
            connectionSuccess( new Event( "success" ) );
        break;
        case "NetConnection.Connect.Failed":
            connectionFailed( new Event( "failed" ) );
        break;
		case "NetStream.Play.Stop":
//			trace("netStatusHandler:code: " + e.info.code);
		break;
        default:
			//trace( "netStatusHandler:code: " + e.info.code );
        break;
    }
}
function connectionSuccess( e:Event ):void {	
	//A. Assign that a NetConnection has been made
	isConnected = true;
	//B. Assign a new NetStream connection
	if( ns == null ){
		ns = new NetStream(nc);
		ns.addEventListener( AsyncErrorEvent.ASYNC_ERROR, catchAll );
		ns.addEventListener( NetStatusEvent.NET_STATUS, netStatusHandler );
		ns.addEventListener( IOErrorEvent.IO_ERROR, catchAll );
	}
	//C. Assign a new ID3 Netstream Connection
	if( id3_ns == null ) {
		id3_ns = new NetStream(nc);
		id3_ns.addEventListener( AsyncErrorEvent.ASYNC_ERROR, catchAll );
		id3_ns.addEventListener( IOErrorEvent.IO_ERROR, catchAll );
		id3_ns.addEventListener( NetStatusEvent.NET_STATUS, netStatusHandler );
	}
	playSong(0);
}
function connectionFailed( e:Event ):void {
    isConnected = false;
}
function catchAll( e:Event ){
	trace("\n\n\n\nCatch All: " + e + "\n\n\n\n");
}
 
/*******************************
Single callback functions that process the information sent by FMS2
*******************************/
nsClient.onPlayStatus	= function( obj:Object ):void{
	switch ( obj.code ){
		case "NetStream.Play.Switch":
		break;
		case "NetStream.Play.Complete":
			soundCompleteHandler();
		break;		
		default:
			for( var a:String in obj ){ trace(a + " " + obj[ a ]); }
		break;
	}
}
id3Client.onId3 = function( obj:Object ):void{
	if(obj["artist"] != undefined){
		text_txt.text = "Artist: " + obj["artist"].toString();
	}
	if(obj["songtitle"] != undefined){
		text_txt.text += "\nTitle: " + obj["songtitle"].toString()
	}	
	for( var b:String in obj ) {
		//trace(b + ": " + obj[ b ]);
	}
}
function setNetClientLength(length:Number):void{
	nsClient.length = length;
}	
/*******************************
Song
*******************************/
function prevSong():void {
	//A. Close NetStream connection to allow for a new one
	ns.close();
	//B. If there is no previous song to play, restart the currentSong
	if (currentSong > 0) { 
		currentSong--; 
	} else {
		currentSong = songList.length - 1;
	}
	//C. Create a new Net Stream. The new Event is simply Fluff
	connectionSuccess( new Event("Empty String"));
}
function nextSong():void {
	//A. Close the NetStream connection to allow for a new one
	ns.close();
	//B. If there is another song in the playlist, play on!
	if (currentSong < songList.length - 1) {
		currentSong++;
	}else {
	//C. Otherwise return to the first song on the playlist
		currentSong = 0;
	}
	//D. Create a new NetStream connection
	connectionSuccess(new Event("Empty String"));
}
function playSong(position:Number):void {
	text_txt.text = "";
	//A. Ensure that the connection to FMS is open
	if (!isConnected) { createConnection(rtmp); }
	//B. Find the ID3 Information of the Mp3
	id3_ns.play("id3:" + songList[currentSong]);
	//C. Reassign the id3Client:Object to re-catch any ID3 info
	id3_ns.client = id3Client;
	//C. Play the new NetStream connection
	//play(songName, postion in Seconds:Number, duration in seconds:Number, flush:Boolean -> false means play the next song)
	ns.play("mp3:" + songList[currentSong], position);
	//D. Reassign the nsClient:Object to ensure the catch of the onPlayStatus
	ns.client = nsClient;
	//E. Adjust the Volume
	ns.soundTransform = soundXForm;
	//E. Retreive the Length of the Song from FMS and set it to nsClient.length
	nc.call("getStreamLength", new Responder(setNetClientLength), "mp3:" + songList[currentSong]);
	//F. Begin tracking the position of the song for the status bar
	seekBar_mc.addEventListener(Event.ENTER_FRAME, songPosition);
}
function pauseSong():void {
		ns.togglePause();		
}
function soundCompleteHandler():void {
	trace("soundCompleteHandler");
	//Garbage Collection
	seekBar_mc.removeEventListener(Event.ENTER_FRAME, songPosition);
	//This resets the Progress Bar back to 0
	songPosition(new Event("Empty String"));
	//Flip the Play/Pause button back to play
	play_mc.gotoAndStop("play");
	//Repeat the song
	nextSong();
}
/*******************************
Volume
*******************************/
function volStartDrag(e:MouseEvent):void {
	volumeUpdate(e);
	volBar_mc.addEventListener(MouseEvent.MOUSE_MOVE, volumeUpdate);
	volScrub_mc.addEventListener(MouseEvent.MOUSE_MOVE, volumeUpdate);
	stage.addEventListener(MouseEvent.MOUSE_UP, volumeStopDrag);
}
function volumeStopDrag(e:MouseEvent):void {
	volBar_mc.removeEventListener(MouseEvent.MOUSE_MOVE, volumeUpdate);
	volScrub_mc.removeEventListener(MouseEvent.MOUSE_MOVE, volumeUpdate);
	stage.removeEventListener(MouseEvent.MOUSE_UP, volumeStopDrag);
}
function volumeUpdate(e:MouseEvent):void{
		//Calculate the Distance Between the Mouse (e.stageX) and the volBar_mc.x
		var dist:Number = ((e.stageX - volBar_mc.x) / volBar_mc.width);
		if (dist >= 0 && dist <= 1){
			//Adjust the Volume Bar GUI
			volumeBarUpdate(dist);
			//Adjust the Sound Volume
			soundXForm.volume = dist;
			ns.soundTransform = soundXForm;	
		}		
}
function volumeBarUpdate(dist:Number):void{
	volScrub_mc.scaleX = (dist);
}
/*******************************
Seek
*******************************/
function seekStartDrag(e:MouseEvent):void {
	//A. Jump to the spot in the song where the user clicked
	seekUpdate(e);
	//A. Remain seeking while the Mouse is Still Down and Moving
	seekBar_mc.addEventListener(MouseEvent.MOUSE_MOVE, seekUpdate);
	seekScrub_mc.addEventListener(MouseEvent.MOUSE_MOVE, seekUpdate);
	//C. Self Destruct
	stage.addEventListener(MouseEvent.MOUSE_UP, seekStopDrag);
}
function seekStopDrag(e:Event):void {
	seekScrub_mc.removeEventListener(MouseEvent.MOUSE_MOVE, seekUpdate);
	seekBar_mc.removeEventListener(MouseEvent.MOUSE_MOVE, seekUpdate);
	stage.removeEventListener(MouseEvent.MOUSE_UP, seekStopDrag);
}
function seekUpdate(e:MouseEvent):void {
	//A. If a user clicks a new part of the song, you must first seek() then update the Progress Bar
	var dist:Number = ((e.stageX - seekBar_mc.x) / seekBar_mc.width);
	//B. Seek the spot
	ns.seek(Math.floor(nsClient.length * dist));
	//C. Upate the Progress Bar
	seekBarUpdate(dist)
}
function songPosition(e:Event):void{
	var dist:Number = ns.time / nsClient.length;
	if (!isNaN(dist)) {
		seekBarUpdate(dist);
	} else {
		seekBarUpdate(0);
	}	
}
function seekBarUpdate(dist:Number){
	//A. Adjust the GUI
	seekScrub_mc.scaleX = dist;
}
/*******************************
Launch the Application on Frame(0)
*******************************/
addFrameScript(0, createConnection(rtmp));