Friday, November 30, 2012

Streaming a FLV video with AS3/Flash/Flex from a URL without a Streaming Server


Here's a code snippet to stream a FLV from a random source without a RTMP streaming server like Red 5/ FMS.

//You'll have to add the necessary imports

private var _video:Video; //Our video object

_video = new Video(640, 480);

private var _netConnection:NetConnection = new NetConnection();
_netConnection.connect(null); //No need of specifying a RTMP server!


private var _ns:NetStream = new NetStream(_netConnection);

_ns.addEventListener(NetStatusEvent.NET_STATUS, handleNetStatusPlay, false, 0, true);

_video.attachNetStream(_ns); //Attach our NetStream to our video object

_ns.client = new NetStreamUserClient(_ns);
var streamPath:String = "http://www.flvFilesSite.com/myFolder/myTestFLV.flv";
_ns.play(streamPath);



//Handle our NetStatusEvent
private function handleNetStatusPlay(e:NetStatusEvent):void
{

 if (e.info.level == "error")
 {
  if (e.info.code == "NetStream.Play.StreamNotFound")
  {
   trace("FLV file does not exist!");
  }
 }
}









Code for NetStreamUserClient
package
{
 import flash.net.NetStream;
 
 /**
  * ...
  * @author Rajesh Peter Douglas D'Monte
  */
 public class NetStreamUserClient
 {
  public function NetStreamUserClient()
  {
  }
  
  public function onCuePoint(infoObject:Object):void
  {
   trace("onCuePoint" + infoObject);
  }
  
  public function onMetaData(infoObject:Object):void
  {
   trace("onMetaData " + infoObject);
  }
  
  public function onPlayStatus(infoObject:Object):void
  {
   trace("onPlayStatus " + infoObject);
   //Debug.print_r(infoObject);
   if (infoObject.code == "NetStream.Play.Complete")
   {
    //FLV finished playing
   }
  }
 }
}
There are some formatting issues 'cause I haven't figured out how to display code properly on my blog.

No comments: