This example shows how to have the server detect the length of a stream.
A client might need to retrieve the length of a stream stored on the server, for example, if a Flash CS3 presentation displays the length of a video to let the user decide whether to play it.
To do this, define a method in server-side code that calls Stream.length(), and then have the client call it using NetConnection.call().
In main.asc, define a function on the client object that calls Stream.length(). Do this within the onConnect handler:
application.onConnect = function( client ) {
client.getStreamLength = function( streamName ) {
trace("length is " + Stream.length( streamName ));
return Stream.length( streamName );
}
application.acceptConnection( client );
}
From the main client class, you call getStreamLength() in the server-side code. You need to create a Responder object to hold the response:
var responder:Responder = new Responder(onResult);
This line specifies that the onResult() function will handle the result. You also need to write onResult(), as shown in the following steps.
package {
import flash.display.Sprite;
import flash.net.NetConnection;
import flash.events.NetStatusEvent;
import flash.net.NetStream;
import flash.net.Responder;
import flash.media.Video;
...
public class StreamLength extends Sprite
{
var nc:NetConnection;
var stream:NetStream;
var video:Video;
var responder:Responder;
}
...
public function StreamLength()
{
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
nc.connect("rtmp://localhost/StreamLength");
}
private function netStatusHandler(event:NetStatusEvent):void
{
trace("connected is: " + nc.connected );
trace("event.info.level: " + event.info.level);
trace("event.info.code: " + event.info.code);
switch (event.info.code)
{
case "NetConnection.Connect.Success":
trace("Congratulations! you're connected");
connectStream(nc);
break;
case "NetConnection.Connect.Rejected":
case "NetConnection.Connect.Failed":
trace ("Oops! the connection was rejected");
break;
}
}
// play a recorded stream on the server
private function connectStream(nc:NetConnection):void {
stream = new NetStream(nc);
stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
stream.client = new CustomClient();
responder = new Responder(onResult);
nc.call("getStreamLength", responder, "bikes" );
}
private function onResult(result:Object):void {
trace("The stream length is " + result + " seconds");
output.text = "The stream length is " + result + " seconds";
}
Write the client event handler class
As usual with playing a stream, write a separate class to handle the onMetaData and onPlayStatus events:
class CustomClient {
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 {
trace("handling playstatus here");
}
}