AIR app:How to load swf from server - actionscript-3

My app structure is below:
(local)
Login.swf
(server)
Main.swf
assets1.swf
assets2.swf
Login.swf -> Main.swf (OK!)
Main.swf -> assets1&2.swf (fail!, downloaded but not trigger complete event)
-progress event: bytes:loaded==total
Why?
How can i load assets from server using Main.swf?
I found somebody say it is crossdomain problem...then how to solve?
var _loader:Loader = new Loader();
var context:LoaderContext = new LoaderContext();
context.allowCodeImport = true;
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete_handler);
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loader_progress_handler);
_loader.loadBytes(_urlloader.data,context);
Thanks!

BE AWARE:
On mobile it only works on Android... iOS due to a security policy does not permit to load an swf inside another one.
Said that you can surerly load an SWF.
First of all we need to understand if you can download the SWF bytearray using the URLLoader.
if yes you can load the swf in a two step routine..
hope this help :)
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
showStatusBar="false"
creationComplete="downloadSwf()">
<fx:Script>
<![CDATA[
import mx.core.FlexGlobals;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.managers.SystemManager;
import spark.components.Application;
private function downloadSwf():void {
// load the file with URLLoader into a bytearray
sfwLoader.visible = false;
var loader:URLLoader = new URLLoader();
// binary format since it a SWF
loader.dataFormat=URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, onSWFLoaded);
loader.addEventListener(IOErrorEvent.IO_ERROR, cantConnect);
//load the file
loader.load(new URLRequest("url"));
}
private function cantConnect(e:IOErrorEvent):void
{
var loader:URLLoader=URLLoader(e.target);
loader.removeEventListener(Event.COMPLETE, onSWFLoaded);
loader.removeEventListener(IOErrorEvent.IO_ERROR, cantConnect);
// error handling
return;
}
private function onSWFLoaded(e:Event):void {
// remove the event
var loader:URLLoader=URLLoader(e.target);
loader.removeEventListener(Event.COMPLETE, onSWFLoaded);
loader.removeEventListener(IOErrorEvent.IO_ERROR, cantConnect);
// add an Application context and allow bytecode execution
var context:LoaderContext=new LoaderContext();
context.allowLoadBytesCodeExecution=true;
// set the new context on SWFLoader
sfwLoader.loaderContext = context;
sfwLoader.addEventListener(Event.COMPLETE, loadComplete);
// load the data from the bytearray
sfwLoader.load(loader.data);
}
// your load complete function
private function loadComplete(completeEvent:Event):void {
sfwLoader.removeEventListener(Event.COMPLETE, loadComplete);
var swfApplication:* = completeEvent.target.content;
var sysmgr:SystemManager = (swfApplication as SystemManager);
sysmgr.addEventListener(FlexEvent.APPLICATION_COMPLETE, swfAppComplete);
}
private function swfAppComplete(event:FlexEvent):void {
sfwLoader.visible = true;
var sysmgr:SystemManager = (event.currentTarget as SystemManager);
sysmgr.removeEventListener(FlexEvent.APPLICATION_COMPLETE, swfAppComplete);
var swfApp:Application = (sysmgr.application as Application);
if (!swfApp.hasOwnProperty("version")) {
return;
}
// version is a public property in the main of the loaded application
var verion:String = swfApp["version"];
swfApp.addEventListener(Event.CLOSE, appClose);
}
private function appClose(e:Event):void
{
sfwLoader.unloadAndStop(true);
NativeApplication.nativeApplication.exit();
}
private function closeApp(e:CloseEvent):void
{
try{
(FlexGlobals.topLevelApplication as WindowedApplication).close();
}
catch(e:Error){}
}
]]>
</fx:Script>
<mx:SWFLoader id="sfwLoader"
width="100%" visible="false"
height="100%"/>
</s:WindowedApplication>

Related

Playing a video with flex, AS3

I am currently trying to make a game on flex and one of the problems I ran in to is how to play a short animation at the beginning. This is what I have so far:
Game.mxml
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
name="Game"
backgroundColor="#000000"
horizontalAlign="center"
creationComplete="Init();"
enterFrame="UpdateFrame();"
paddingLeft="0"
paddingTop="0"
paddingBottom="0"
paddingRight="0"
width="800" height="600">
<mx:Script>
<![CDATA[
include "Game.as";
]]>
</mx:Script>
<mx:Canvas id="gamePanel" x="0" y="0" width="100%" height="100%" mouseDown="MouseDown(event)" mouseUp="MouseUp(event)" mouseMove="MouseMoved(event)"/>
</mx:Application>
and Game.as
import flash.display.*;
import flash.events.*;
import flash.external.ExternalInterface;
import mx.events.*;
import mx.controls.*;
[Embed(source="MyVideoClip.flv")] private var MyVideoClip:Class;
public function Init():void
{
var MyVideo:Video = new Video(800, 600);
addChild(MyVideo);
var qNetConnection:NetConnection = new NetConnection();
qNetConnection.connect(null);
var qNetStream:NetStream = new NetStream(qNetConnection);
MyVideo.attachNetStream(qNetStream);
qNetStream.client = new Object();
qNetStream.play(MyVideoClip);
}
private function UpdateFrame():void
{
}
private function MouseDown(event:MouseEvent):void
{
}
private function MouseUp(event:MouseEvent):void
{
}
private function MouseMoved(event:MouseEvent):void
{
}
I am rather new to Flex and AS3 so most of this code was ripped off web tutorials. Whenever I try to compile it I get: 'Error: 'MyVideoClip.flv' does no have a recongnized extention, and a mimeType was not provided. Error: unable to transcode 'MyVideoClip.flv''
If I remove the 'embed' line and replace MyVideoClip with "MyVideoClip.flv" in the play() function, the code compiles with no errors, but when I open the SWF all I get is a black screen. What am I doing terribly wrong?
Thanks in advance!!
Try setting the mime-type, e.g.:
[Embed(source = "MyVideoClip.flv", mimeType = "application/octet-stream")]
You embedded the video file (its bytes) into the output SWF. So now NetStream must play from a bytes source. Just set a byteArray as equal to new MyVideoClip(); and append to NetStream.
Try this...
[Embed(source="MyVideoClip.flv", mimeType="application/octet-stream")] private var MyVideoClip:Class; //# embed the FLV's bytes
public var VideoClipBytes : ByteArray;
public var MyVideo:Video;
public var qNetConnection:NetConnection;
public var qNetStream:NetStream;
public function Init():void
{
VideoClipBytes = new MyVideoClip() as ByteArray; //# fill a byte Array with embedded bytes
qNetConnection = new NetConnection(); qNetConnection.connect(null);
qNetStream = new NetStream(qNetConnection);
qNetStream.client = new Object();
MyVideo = new Video(800, 600);
MyVideo.attachNetStream(qNetStream);
addChild(MyVideo);
qNetStream.play(null); //# play mode is now bytes
qNetStream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN); //# ready for new audio/video data
qNetStream.appendBytes( VideoClipBytes ); //# add bytes to decoder queue (playback)
}
PS : I made some of your variables as public so later you can access & control them from any other functions. Remember if you make var inside a public function it stays valid only in that one function and doesn't exist to other functions. Best make such vars as publicly available to all functions.

Flex 4 - How to load XML file programmatically?

I have done my EmployeeDetails application using HTTPService. But I want to load my XML file programmatically. I tried it using URLLoader and URLRequest. But no luck. I couldn't done it.
Sample code using HTTPService:
<fx:Declarations>
<s:XMLListCollection id="employeeXMLList" filterFunction="xmlListCollectionFilterFun"/>
<s:HTTPService id="employeeService" url="http://localhost/demo/TextXmlFile.xml"
method="POST" result="employeeService_resultHandler(event)"
fault="employeeService_faultHandler(event)"
resultFormat="xml"/>
</fx:Declarations>
<fx:Script>
<![CDATA[
protected function employeeService_resultHandler(event:ResultEvent):void
{
var xmlList:XMLList = XML(event.result).Employee;
employeeXMLList = new XMLListCollection(xmlList);
}
protected function employeeService_faultHandler(event:FaultEvent):void
{
spark.components.Alert.show(event.fault.faultString,"Fault Error Message");
}
]]>
</fx:Script>
It's working well.
Now I change this as follows:
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:components="components.*"
minWidth="955" minHeight="600"
creationComplete="load()">
<fx:Script>
<![CDATA[
private var request:URLRequest = new URLRequest("http://localhost/demo/TextXmlFile.xml");
//request.contentType = "XML";
//request.method = URLRequestMethod.POST;
private var xmlData:XML;
private var loader:URLLoader = new URLLoader();
private function loadXML(event:Event):void
{
xmlData = new XML(event.target.date);
}
private function load():void
{
loader.addEventListener(Event.COMPLETE, loadXML);
loader.load(request);
}
]]>
</fx:Script>
And I don't know what I am done here. Anyone can tell me the correct way to do this? And Please give me some explanation for that?
My XML:
<?xml version="1.0" encoding="UTF-8"?>
<CompanyEmployees version="1">
<Employee>
<Name>John</Name>
<Id>234</Id>
<DOB>1990/04/02</DOB>
<Designation>Project manager</Designation>
<Department>Mobile</Department>
<DOJ>2008/04/11</DOJ>
<Experience>15</Experience>
<Mobile>9999999999</Mobile>
<Email>john.a#Sybrant.com</Email>
</Employee>
<Employee>
<Name>Adya</Name>
<Id>135</Id>
<DOB>1989/04/21</DOB>
<Designation>Software Engineer</Designation>
<Department>Flex</Department>
<DOJ>2009/05/15</DOJ>
<Experience>5</Experience>
<Mobile>76890678990</Mobile>
<Email>adya#Sybrant.com</Email>
</Employee>
</CompanyEmployees>
UPDATE
private var urlRequest:URLRequest;
urlRequest = new URLRequest("http://localhost/TextXmlFile.xml");
urlRequest.contentType = "XML";
urlRequest.method = URLRequestMethod.POST;
I am getting error like "Access of undefined property urlRequest."
It seems to be typo error.
private var request:URLRequest;
private var xmlData:XML;
private var loader:URLLoader = new URLLoader();
private function loadXML(event:Event):void
{
xmlData = new XML(event.target.data); //Note here data instead of date.
}
private function load():void
{
request = new URLRequest("http://localhost/demo/TextXmlFile.xml");
request.contentType = "XML";
request.method = URLRequestMethod.POST;
loader.addEventListener(Event.COMPLETE, loadXML);
loader.load(request);
}
Reason :
You can only do declare and initialize/instantiate object out side of functions.
Normally compiler expect out side of function should be variable declaration(protected/public/private). So we can't assign value of those at out of function like
request.contentType = "XML";
request.method = URLRequestMethod.POST;
This is exact place where function comes in. Sometime it is possible with static block if all neccessary function and variable should be static.
More details about AS3 Static Block https://www.google.co.in/search?q=static+block+in+as3
or Check out SO Can we use static initializers in a Flex Library?
Check docs: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLLoader.html

How to convert a string to an object

I'm trying to use a sharedObject to coordinate the movement of several objects on the stage between multiple game players. I think that I'm very close but I seem to be having a problem converting a string stored in the sharedObject into an instance of the Ball class.
My problem is in the soSync function.
I think I need to convert into an object the value of 'objectMoved' that is stored in the sharedObject. I can trace the name of the selected object, but I cannot retrieve it as an object.
How do I store the selected object in a sharedObject and then use it to coordinate motion with the other game players?
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
public var nc:NetConnection;
private var connectionURL:String = "rtmp://server address...";
public var remoteSO:SharedObject;
private var checker:Ball;
public function init():void{
//Create new checkers; place them and create listeners
for (var i:int = 0; i < 3; i++){
checker = new Ball;
checker.x = 150 + (i * 110);
checker.y = 150;
checker.name = String(i);
this.addChild(checker);
checker.addEventListener(MouseEvent.MOUSE_DOWN,handleMouseDown);
}
// Establish connection to the server
nc = new NetConnection();
//Listener triggered by the NetConnection connection
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
nc.connect(connectionURL);
}
private function netStatusHandler(e:NetStatusEvent):void {
if(e.info.code == "NetConnection.Connect.Success"){
createRemoteSO();
}
}
private function handleMouseDown(e:MouseEvent):void{
//Show which object has been selected
objectInfo.text = "Clicked: "+String(e.currentTarget);
e.currentTarget.startDrag();
e.currentTarget.addEventListener(MouseEvent.MOUSE_MOVE,dragging);
e.currentTarget.addEventListener(MouseEvent.MOUSE_UP,handleMouseUp)
//Update the remote shared object from this client
function dragging(e:MouseEvent):void{
objectInfo.text = "Dragging: "+String(e.currentTarget);
//Set the shared object
remoteSO.setProperty("objectMoved",e.currentTarget.name);
remoteSO.setProperty("x",e.currentTarget.x);
remoteSO.setProperty("y",e.currentTarget.y);
}
function handleMouseUp(e:MouseEvent):void{
e.currentTarget.stopDrag();
objectInfo.text = ""
e.currentTarget.removeEventListener(MouseEvent.MOUSE_MOVE,dragging)
}
}
private function createRemoteSO():void{
// Create reference to the remote shared object
remoteSO = SharedObject.getRemote("remoteSO",nc.uri,false);
remoteSO.connect(nc);
//Listener to handle changes to the remote shared object
remoteSO.addEventListener(SyncEvent.SYNC, soSync);
}
//Called when a change is made to the remote shared object by other clients
private var counter:int;
private function soSync(se:SyncEvent):void {
if(remoteSO.data.objectMoved){
this.getChildByName(remoteSO.data.objectMoved).x = remoteSO.data.x;
this.getChildByName(remoteSO.data.objectMoved).y = remoteSO.data.y;
}else{
trace("Object does not exist")
}
}
]]>
</mx:Script>
<mx:Text x="147" y="51" text="Selected object"/>
<mx:TextArea id="objectInfo" x="237" y="50"/>
</mx:Application>
Ball.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:UIComponent xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.events.FlexEvent;
private function init():void{
var child:Shape = new Shape();
child.graphics.beginFill(0xff0000, .5);
child.graphics.drawCircle(0, 0, 50);
child.graphics.endFill();
this.addChild(child);
}
]]>
</mx:Script>
</mx:UIComponent>
I think you could use getChildByName("String/ObjectName here").
So in your case...
this.getChildByName(remoteSO.data.objectMoved).y = remoteSO.data.y;
Alternatively, could you not just add the physical object itself when using setProperty as opposed to the objects name. Like so...
remoteSO.setProperty("objectMoved",e.currentTarget);
Your Ball object seems to be a DisplayObject, which are unable to be saved in a shared object as a whole. You can, however, instantiate a Ball object, read properties out of the SO and assign them to your ball. The properties in question seem to be x and y, and not objectMoved, as your ball's name will most likely be in line of instance389 which does not spell a thing if you lose the naming context, and even if not, you can only find a child by name if it still exists. So, if you have only one object of type Ball, you assign it the X and Y read from the SO, if not, you should store several balls in your SO, so you will instantiate them later and preserve all of their coordinates.

Adobe record sound and save

In the following code i am trying to save the microphone contents to a file.The saved file doesn't play and Every time the file is saved i see that the size is only of 10 bytes only.What am i doing wrong in the code.Can someone please show me the correct code to save it .And the saved file should play the recorded contents accordingly.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Script>
<![CDATA[
import flash.events.SampleDataEvent;
import flash.media.Microphone;
import flash.net.FileReference;
import mx.controls.Alert;
import flash.net.FileReference;
import flash.display.Sprite;
import flash.media.Sound;
import flash.utils.ByteArray;
import flash.external.ExternalInterface;
public var _file:FileReference = new FileReference();
[Bindable] private var micList:Array;
public var mic:Microphone = Microphone.getMicrophone();
protected var isRecording:Boolean = false;
protected function startMicRecording():void
{
//var mic:Microphone = Microphone.getMicrophone();
mic.gain = 60;
mic.rate = 11;
mic.setUseEchoSuppression(true);
mic.setLoopBack(true);
mic.setSilenceLevel(5, 1000);
Alert.show("In recording");
isRecording = true;
mic.addEventListener(SampleDataEvent.SAMPLE_DATA, gotMicData);
}
protected function stopMicRecording():void
{
//isRecording = false;
try{
//_file.save( SampleDataEvent.SAMPLE_DATA, "recorded.wav" );
_file.save(SampleDataEvent.SAMPLE_DATA , "recorded.flv" );
}
catch(e:Error)
{
Alert.show("In Stopmicrecording"+e);
}
}
private function gotMicData(micData:SampleDataEvent):void
{
//mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, gotMicData);
}
protected var soundRecording:ByteArray;
protected var soundOutput:Sound;
protected function playbackData():void
{
}
private function playSound(soundOutput:SampleDataEvent):void
{
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:ComboBox x="150" id="comboMicList" dataProvider="{micList}" />
<mx:Button x="250" id="startmicrec" label="Start Rec" click="startMicRecording()"/>
<mx:Button x="350" id="stopmicrec" label="Stop Rec" click="stopMicRecording()"/>
<!--<mx:Button x="50" id="setupmic" label="Select Mic" click="setupMicrophone()"/>-->
<mx:Button x="450" id="playrecsound" label="Play sound" click="playbackData()"/>
</s:Application>
You need to store the data that is handed to you in gotMicData into a ByteArray and then save that ByteArray. You are saving the event name, which is a string (10 characters long).
Once you do that, you need to load the file and hand sample data to the sound. You play the sound back 8 times... because you sampled at 11 KHz but the sound plays back at 44 KHz (4x writing) and the sound is Stereo but the mic is mono (2x again).
You can't save the data as a WAV file directly... you recorded raw data. If you want to go through the trouble of writing a proper WAV header, then you don't have to play the games of handing sample data and hand the file to the Sound object. That is an exercise outside of the scope of this question.
Good luck!
import mx.controls.Alert;
public var mic:Microphone = Microphone.getMicrophone();
public var recordedData:ByteArray;
protected function startMicRecording():void
{
mic.gain = 60;
mic.rate = 11;
mic.setUseEchoSuppression(true);
mic.setLoopBack(false);
mic.setSilenceLevel(5, 1000);
recordedData = new ByteArray();
mic.addEventListener(SampleDataEvent.SAMPLE_DATA, gotMicData);
}
protected function stopMicRecording():void
{
mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, gotMicData);
try{
var file:FileReference = new FileReference();
file.save(recordedData, "recorded.dat" );
}
catch(e:Error)
{
Alert.show("In Stopmicrecording"+e);
}
}
private function gotMicData(sample:SampleDataEvent):void
{
recordedData.writeBytes(sample.data, 0, sample.data.bytesAvailable);
}
protected var playbackFile:FileReference;
protected var soundRecording:ByteArray;
protected var soundOutput:Sound;
protected function playbackData():void
{
playbackFile = new FileReference();
playbackFile.addEventListener(Event.SELECT, playbackFileSelected);
playbackFile.browse();
}
private function playbackFileSelected(event:Event):void {
playbackFile.addEventListener(Event.COMPLETE, playbackFileLoaded);
playbackFile.load();
}
private function playbackFileLoaded(event:Event):void {
soundRecording = playbackFile.data;
soundOutput = new Sound();
soundOutput.addEventListener(SampleDataEvent.SAMPLE_DATA, moreInput);
soundOutput.play();
}
private function moreInput(event:SampleDataEvent):void {
var sample:Number;
for (var i:int = 0; i < 1024; i++) {
if (soundRecording.bytesAvailable > 0) {
sample = soundRecording.readFloat();
// write the same byte 8 times:
// Upsample from 11 KHz to 44 KHz (x4)
// Mono to Stereo (x2)
for(var x:int = 0; x < 8; x++)
event.data.writeFloat(sample);
}
}
}

How can I fix this video phone app?

I'm trying to practice making a simple video phone app so I'm trying to make a program to send a video and recieve a video using Cirrus from Adobe. I'm having trouble recieving the stream though. Here is the cod that I'm using:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" applicationComplete="init()">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.core.UIComponent;
import mx.core.mx_internal;
import spark.components.Group;
private const SERVER:String = "rtmfp://p2p.rtmfp.net/";
private const DEVKEY:String = "MY-DEV-KEY";
[Bindable]
//Net Connection variable
private var netConnection:NetConnection;
//Sending video stream var
private var sendStream:NetStream;
//Sending video video var
private var videoSend:Video;
//Receiving video stream var
private var recvStream:NetStream;
//String for getting their ID
private var id_of_publishing_client:String;
private function init():void {
//Setup videoSend
videoSend = new Video(320,240);
videoSend.x = 10;
videoSend.y = 10;
var uic:UIComponent = new UIComponent();
uic.addChild(videoSend);
addElement(uic);
//connect
connect();
}
private function connect():void{
netConnection = new NetConnection();
netConnection.addEventListener(NetStatusEvent.NET_STATUS, netStreamHandler);
netConnection.connect(SERVER,DEVKEY);
}
private function setupStreamOutgoing():void{
//Send Stream setting up
sendStream = new NetStream(netConnection, NetStream.DIRECT_CONNECTIONS);
sendStream.addEventListener(NetStatusEvent.NET_STATUS,netStreamHandler);
//setup camera
var cam:Camera = Camera.getCamera();
//attach the camera to the to the sendStream
sendStream.attachCamera(cam);
//publish the sendStream
sendStream.publish("media");
//attach the camera to the videoStream object
videoSend.attachCamera(cam);
}
private function getVideoReceiver():void{
id_of_publishing_client = theirID.text;
writeText("inside getVideoReceiver()");
if(id_of_publishing_client){
recvStream = new NetStream(netConnection, id_of_publishing_client);
recvStream.addEventListener(NetStatusEvent.NET_STATUS, netStreamHandler);
writeText("flag");
//play the recvStream
recvStream.play("media");
writeText("recvStream.play(media)");
//attach the stream to the myVid
myVid.mx_internal::videoPlayer.attachNetStream(recvStream);
}
else {
theirID.text = "Please place an ID here.";
}
}
private function netStreamHandler(event:NetStatusEvent):void{
writeText(event.info.code);
switch(event.info.code){
case "NetConnection.Connect.Success":
//Display my ID in myID.text
myID.text = netConnection.nearID;
setupStreamOutgoing();
break;
case "NetStream.Connect.Success":
break;
case "NetStream.Connect.Closed":
break;
}
}
private function writeText(txt:String):void{
txtHistory.text += txt+"\n";
}
]]>
</fx:Script>
<s:TextArea top="10" bottom="10" id="txtHistory" width="252" right="10"/>
<s:TextInput id="theirID" x="112" y="342" width="437"/>
<s:TextInput id="myID" x="112" y="312" width="437"/>
<s:Button x="10" y="312" label="My Connection" width="94" />
<s:Button x="10" y="341" label="Their Connection" width="94" click="getVideoReceiver()"/>
<mx:VideoDisplay id="myVid"
x="340"
y="10"
width="320" height="240" />
</s:Application>
Inside of the getVideoReveiver() function I'm getting the flag to go off from writeText("flag") then I get and output in the text box of:
NetStream.Play.Reset
NetStream.Play.Start
from the netStreamHandler, but the video never shows up in the receiving video element.
I'm running this is two different videos of the same computer and taking the nearID from one stream and pasting it into the textInput theirID. I'm not sure what to try next?
Here is the script that I got working for anyone who would like this as an example. All you need is a Cirrus dev key.
<fx:Script>
<![CDATA[
import mx.core.UIComponent;
import mx.core.mx_internal;
import flash.display.MovieClip;
import flash.events.*;
import flash.net.*;
import spark.components.Group;
private const SERVER:String = "rtmfp://p2p.rtmfp.net/";
private const DEVKEY:String = "YOUR-DEV-KEY";
[Bindable]
//Net Connection variable that is needed to s
private var netConnection:NetConnection;
//Sending video stream var
private var sendStream:NetStream;
//Sending video video var
private var videoSend:Video;
//receiving video video var
private var videoRecv:Video;
//Receiving video stream var
private var recvStream:NetStream;
//String for getting their ID
private var id_of_publishing_client:String;
private function init():void {
//Setup videoSend
videoSend = new Video(320,240);
videoSend.x = 10;
videoSend.y = 10;
//Setup videoRecv
videoRecv = new Video(320,240);
videoRecv.x = 340;
videoRecv.y = 10;
var uic:UIComponent = new UIComponent();
uic.addChild(videoSend);
uic.addChild(videoRecv);
addElement(uic);
//connect to cirrus
connect();
}
private function connect():void{
netConnection = new NetConnection();
netConnection.addEventListener(NetStatusEvent.NET_STATUS, netStreamHandler);
netConnection.connect(SERVER,DEVKEY);
}
private function setupStreamOutgoing():void{
//Send Stream setting up
sendStream = new NetStream(netConnection, NetStream.DIRECT_CONNECTIONS);
sendStream.addEventListener(NetStatusEvent.NET_STATUS,netStreamHandler);
//setup camera
var cam:Camera = Camera.getCamera();
//attach the camera to the to the sendStream
sendStream.attachCamera(cam);
//publish the sendStream
sendStream.publish("media");
//attach the camera to the videoStream object
videoSend.attachCamera(cam);
}
private function getVideoReceiver():void{
id_of_publishing_client = theirID.text;
writeText("inside getVideoReceiver()");
if(id_of_publishing_client){
recvStream = new NetStream(netConnection, id_of_publishing_client);
recvStream.addEventListener(NetStatusEvent.NET_STATUS, netStreamHandler);
writeText("flag");
//play the recvStream
recvStream.play("media");
writeText("recvStream.play(media)");
//attach the stream videoRecv
videoRecv.attachNetStream(recvStream);
}
else {
theirID.text = "Please place an ID here.";
}
}
private function netStreamHandler(event:NetStatusEvent):void{
writeText(event.info.code);
switch(event.info.code){
case "NetConnection.Connect.Success":
//Display my ID in myID.text
myID.text = netConnection.nearID;
setupStreamOutgoing();
break;
case "NetStream.Connect.Success":
break;
case "NetStream.Connect.Closed":
break;
case "NetStream.Play.Start":
break;
}
}
private function writeText(txt:String):void{
txtHistory.text += txt+"\n";
}
]]>
</fx:Script>
<s:TextArea top="10" bottom="10" id="txtHistory" width="252" right="10"/>
<s:TextInput id="theirID" x="112" y="342" width="437"/>
<s:TextInput id="myID" x="112" y="312" width="437"/>
<s:Button x="10" y="312" label="My Connection" width="94" />
<s:Button x="10" y="341" label="Their Connection" width="94" click="getVideoReceiver()"/>