This example shows how to detect buffer events and adjust the buffer time dynamically, as events occur. Highlights of the code are shown here; to see the complete sample, see the Buffer.as sample file. To run the sample, see the general instructions in Deploy an application.
To change the buffer time, use NetStream.setBufferTime() to set a value in seconds, for example:
ns.setBufferTime(2);
Two seconds is a good buffer size for fast connections; 10 seconds is a good buffer size for slow connections.
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
nc.connect("rtmp://localhost/Buffer");
private function netStatusHandler(event:NetStatusEvent):void {
switch (event.info.code) {
case "NetConnection.Connect.Success":
trace("The connection was successful");
connectStream(nc);
break;
case "NetConnection.Connect.Failed":
trace("The connection failed");
break;
case "NetConnection.Connect.Rejected":
trace("The connection was rejected");
break;
case "NetStream.Buffer.Full":
ns.bufferTime = 10;
trace("Expanded buffer to 10");
break;
case "NetStream.Buffer.Empty":
ns.bufferTime = 2;
trace("Reduced buffer to 2");
break;
}
}
private function connectStream(nc:NetConnection):void {
ns = new NetStream(nc);
ns.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
ns.client = new CustomClient();
video = new Video();
video.attachNetStream(ns);
ns.play( "bikes", 0 );
ns.bufferTime = 2;
trace("Set an initial buffer time of 2");
addChild(video);
}
Write the client event handler class
As usual when you stream video, write a separate client class that implements the onMetaData() and onPlayStatus() event handlers:
public function onMetaData(info:Object):void {
trace("Metadata: duration=" + info.duration + " width=" + info.width + " height=" + info.height + " framerate=" + info.framerate);
}
public function onPlayStatus(info:Object):void {
switch (info.code) {
case "NetStream.Play.Complete":
trace("The stream has completed");
break;
}
}
These event handlers are needed when you call NetStream.play().