How to play an m4a sound file - actionscript-3

The code below imports and controls an mp3 sound file. When I change from an mp3 to an m4a file the code does not work. Do I need to use a different class to play an m4a file?
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" minWidth="955" minHeight="600" creationComplete="init()" >
<mx:Script>
<![CDATA[
import mx.events.ItemClickEvent;
import mx.rpc.events.ResultEvent;
private var sound:Sound;
private var soundChannel:SoundChannel = new SoundChannel;
private var loaderContext:SoundLoaderContext;
private var trackPosition:Number = 0;
private var timer:Timer;
private var leftGraphic:Sprite;
private var rightGraphic:Sprite;
private function init():void{
var audioFile:String = "recording.mp3";
sound = new Sound(new URLRequest(audioFile));
sound.addEventListener(Event.COMPLETE, onSoundLoaded);
function onSoundLoaded(event:Event):void{
maxTime.text = convertMillesecs(sound.length)
trackSlider.y-= 5;
trackSlider.maximum = sound.length;
}
}
private var counter:Number
private function soundComplete( e:Event ):void{
maxTime.text = convertMillesecs(soundChannel.position);
maxTime.text = convertMillesecs(sound.length)
}
private function checkTrack(event:Event):void{
// manage track counter
trackSlider.value = soundChannel.position;
currentVal.text = String(convertMillesecs(soundChannel.position));
}
private function convertMillesecs(time:Number):String{
var h:Number = new Number(Math.floor(time/1000/60/60));
var m:Number = new Number(Math.floor(time/1000/60)-(h*60));
var s:Number = new Number(Math.floor(time/1000)-(m*60));
var hours:String;
var minutes:String;
var seconds:String
//minutes and seconds always two digits
if(m.toString().length == 1) {
minutes = "0"+m;
} else {
minutes = m.toString();
}
if(s.toString().length == 1) {
seconds = "0"+s;
} else {
seconds = s.toString();
}
// last two digits represent actual seconds
seconds = seconds.slice(seconds.length-2, seconds.length);
return minutes + ":" + seconds;
}
private function controlChange1(event:MouseEvent):void{
var optionString:String;
switch(event.target.id){
case "playButton":
play();
break;
case "pauseButton":
pause();
break;
default:
break;
}
}
private function play():void{
playButton.visible = false;
pauseButton.visible = true;
timer = new Timer(100);
timer.addEventListener(TimerEvent.TIMER, checkTrack);
soundChannel.stop();
soundChannel = sound.play(pausePosition);
timer.start();
}
private var pausePosition:int
private function pause():void{
pausePosition = soundChannel.position;
soundChannel.stop();
playButton.visible = true;
pauseButton.visible = false;
}
private function onTrackSliderChange(e:Event):void{
soundChannel.stop()
soundChannel = sound.play(e.target.value * sound.length / trackSlider.maximum);
playButton.visible = false;
pauseButton.visible = true;
}
private function formatButton(val:String):String{
return convertMillesecs(soundChannel.position)
}
]]>
</mx:Script>
<mx:HBox backgroundColor="0x000000" horizontalCenter="0" verticalCenter="0" verticalAlign="middle" horizontalScrollPolicy="off" verticalScrollPolicy="off" >
<mx:Canvas id="controlBar1" paddingLeft="1" buttonMode="true" useHandCursor="true" >
<mx:Button id="pauseButton" width="40" height="40" click="controlChange1(event)" visible="false" color="0x0B333C"/>
<mx:Button id="playButton" width="40" height="40" click="controlChange1(event)" color="0x000000" />
</mx:Canvas>
<mx:Label id="currentVal" text="00:00" color="0xffffff"/>
<mx:HSlider id="trackSlider" height="10" width="500" liveDragging="false" change="onTrackSliderChange(event);"
dataTipFormatFunction="formatButton" showTrackHighlight = "true" mouseEnabled="true" useHandCursor="true" />
<mx:Label id="maxTime" text="00:00" color="0xffffff"/>
</mx:HBox>
</mx:Application>

The Sound class can play one of two formats: mp3 and the raw format AS3 records to. So it is impossible to use the Sound class to play m4a, unfortunately.
Fortunately, it is possible to play m4a using another class: NetStream. You may or may not have as fine of control over it without the SoundTransform and SoundMixer classes, but you can still play the file no problem (I've done it in the past, though it didn't end up working quite the way I was hoping for so I ended up going with mp3s instead)
Adobe Article on m4a playback

Related

Cannot correctly resize an image via action script

Hi I am trying to add an image when I click on a thumbnail.
I know I have to use a listener (Event.COMPLETE ?), but the image is not resizing correctly when I rotate the tablet.
I believe the problem is that I cannot resize the image within the addImage1() function, as the image has not yet loaded, but I cannot use newImg.width within the listener function to reset the image width.
Any help would be most appreciated.
Code follows:-)
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="ZOOM Pictues with Tap"
resize="view1_resizeHandler(event)">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import mx.events.ResizeEvent;
public var hasImageBeenAdded:Boolean = false;
private var imageLastWidth:Number;
private var imageLastHeight:Number;
private var zoomFactor:Number;
private var imageNumber:Number;
private var rhsKeepWidth:int;
private var rhsKeepHeight:int;
private var rhsKeep:Boolean = false;
protected function view1_resizeHandler(event:ResizeEvent):void
{
if(rhsKeepWidth > rhsKeepHeight) // Was Landscape is now Portrait
{
var tmpWidth2:int = rhsKeepWidth;
var tmpHeight2:int = rhsKeepHeight;
rhsKeepWidth = tmpHeight2-lhs.width;
rhsKeepHeight = tmpWidth2+lhs.width;
}
else //Was Portrait is now Landscape
{
var tmpWidth1:int = rhsKeepWidth;
var tmpHeight1:int = rhsKeepHeight;
rhsKeepWidth = tmpHeight1-lhs.width;
rhsKeepHeight = tmpWidth1+lhs.width;
}
addImage1();
}
protected function removeAllImages():void
{
var totalElements : int = rhs.numElements;
for(var i:int=totalElements-1;i>=0;i--)
{
rhs.removeElementAt(i);
}
}
private function onImageLoaded(e:Event):void
{
var zoomFactor1:Number;
var zoomFactor2:Number;
imageLastWidth = e.target.sourceWidth;
imageLastHeight = e.target.sourceHeight;
if(rhsKeep != true) //Need to set the rhs VGroup dimensions
{
rhs.width = hGroup1.width-lhs.width;
rhs.height = hGroup1.height;
rhsKeep = true;
rhsKeepWidth = rhs.width;
rhsKeepHeight = rhs.height;
}
zoomFactor1 = rhsKeepWidth/imageLastWidth;
zoomFactor2 = rhsKeepHeight/imageLastHeight;
if(zoomFactor1 < zoomFactor2)
{
zoomFactor = zoomFactor1;
}
else
{
zoomFactor = zoomFactor2;
}
trace("zoomFactor=" + zoomFactor);
}
public function addImage1():void
{
var i:int;
var newImg:Image = new Image();
removeAllImages();
newImg.source = "images/1.jpg";
newImg.x = 0;
newImg.y = 0;
newImg.addEventListener(Event.COMPLETE,onImageLoaded);
rhs.addElementAt(newImg,0);
hasImageBeenAdded = true;
imageNumber = 1;
trace("Image Width= " + newImg.width);
newImg.scaleX = newImg.scaleY = zoomFactor;
}
]]>
</fx:Script>
<s:HGroup id="hGroup1" width="100%" height="100%">
<s:Scroller id="scrollerL" height="100%">
<s:VGroup id="lhs" width="15%" height="100%" gap="10"
horizontalAlign="center" verticalAlign="top">
<s:Image width="100" height="100" source="thumbs/1.jpg" click="addImage1()"/>
</s:VGroup>
</s:Scroller>
<s:Scroller id="scroller1" height="100%" width="100%">
<s:VGroup id="rhs" height="100%">
</s:VGroup>
</s:Scroller>
</s:HGroup>
</s:View>
Regarding the device orientation, you should use:
trace(Stage.deviceOrientation);
trace(Stage.orientation);
They are read-only strings outputting information regarding the device's and the screen's orientation. You may manually set the stage's orientation:
Stage.setOrientation(StageOrientation.DEFAULT);
Regarding the image loading, you need an eventListener for Event.COMPLETE and you should also cast the content as Image:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(event:Event):void {
trace("Image loaded");
// Handle code here
// Use: (loader.content as Image)
});
loader.load(new URLRequest("images/1.jpg"));

Drag and Drop Image loaded by flex-loader. Original Source should not be removed

yesterday me and my friend Ketan thakkar were working on an issue related with drag drop in flex.
Image can dragged easily if it is has direct your or embedded image.
But if we try to drag image which has a source from flex loader, original image loos the parent and then never go back to its original place. We tried to find the solution and with a good luck we got success.
the code is below. If anyone know why this problem exist please help us.
For now we have managed it this way.
<?xml version="1.0" encoding="utf-8"?>
<mx:Script>
<![CDATA[
import mx.controls.Image;
import mx.core.DragSource;
import mx.core.FlexLoader;
import mx.core.UIComponent;
import mx.events.DragEvent;
import mx.events.FlexEvent;
import mx.graphics.ImageSnapshot;
import mx.managers.DragManager;
private var fl:FlexLoader = new FlexLoader();
private var img1:Image = new Image();
private function doDragEnter(event:DragEvent):void
{
DragManager.acceptDragDrop(UIComponent(event.target));
}
private function doDragDrop(event:DragEvent):void
{
var img:Image;
if (event.dragInitiator.parent == dropCanvas)
img = event.dragInitiator as Image;
else
{
img = new Image();
img.width = img.height = 120;
img.source = img1.source;
img.addEventListener(MouseEvent.MOUSE_DOWN, doDragStart);
dropCanvas.addChild(img);
}
img.x = event.localX - (event.dragSource.dataForFormat("localX") as Number);
img.y = event.localY - (event.dragSource.dataForFormat("localY") as Number);
}
private function doDragStart(event:MouseEvent):void
{
var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(event.currentTarget as IBitmapDrawable);
var imageByteArray:ByteArray = imageSnap.data as ByteArray;
img1.load(imageByteArray);
var dragInitiator:Image = event.currentTarget as Image;
var dragSource:DragSource = new DragSource();
var dragProxy:Image = new Image();
dragProxy.source = img1.source;
dragProxy.x = mouseX-25;
dragProxy.y = mouseY-25;
dragProxy.width = 80;
dragProxy.height= 80;
DragManager.doDrag(dragInitiator, dragSource, event, dragProxy,0,0,1,false);
}
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
fl.contentLoaderInfo.addEventListener(Event.COMPLETE, oncomplete);
fl.load( new URLRequest('assets/1.swf'));
}
private function oncomplete(event:Event):void
{
img.source = fl;
}
]]>
</mx:Script>
<controls:FlexBook width="400" height="200"
itemSize="halfPage">
<controls:content>
<mx:Image id="img" mouseDown="doDragStart(event)" /><!--source="#Embed('assets/Hawk.jpg')"-->
<mx:Image id="img11" mouseDown="doDragStart(event)" /><!--source="#Embed('assets/Hawk.jpg')"-->
<mx:Image id="img2" mouseDown="doDragStart(event)" /><!--source="#Embed('assets/Hawk.jpg')"-->
</controls:content>
</controls:FlexBook>
<mx:Canvas id="dropCanvas" width="100%" height="100%" borderColor="#1C5CC7" dragEnter="doDragEnter(event)" dragDrop="doDragDrop(event)" borderStyle="solid" cornerRadius="20" borderThickness="6" backgroundColor="#7E92FC"/>
<!--<mx:Image id="dropImage" source="assets/1.swf" />-->
I had a similar problem, the problem is in this line:
dragProxy.source = img1.source;
you should to copy bitmap img1 like here instead linking it.

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);
}
}
}

red5 streaming connection to flex

I installed red5 successfully, but when I try to connect to red5 to stream a video, the connection fails. If I use netstreaming(null), it works, but when I use red5, it doesn't.
I use following code to connect the stream:
<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" creationComplete="init();">
<fx:Script>
<![CDATA[
import mx.utils.ObjectUtil;
private var nc:NetConnection;
private var ns:NetStream;
private var video:Video;
private var meta:Object;
private var videoURL:String = "Fleximagteaser.flv";
private var nc1:NetConnection;
private var ns1:NetStream;
private var video1:Video;
private var meta1:Object;
private function init():void {
//video1
var nsClient:Object = {};
nsClient.onMetaData = ns_onMetaData;
nsClient.onCuePoint = ns_onCuePoint;
nc = new NetConnection();
nc.connect("rtmp://localhost/demo");
ns = new NetStream(nc);
ns.play(videoURL);
ns.client = nsClient;
video = new Video();
video.attachNetStream(ns);
uic.addChild(video);
}
private function ns_onMetaData(item:Object):void {
trace("meta");
meta = item;
// Resize Video object to same size as meta data.
video.width = item.width;
video.height = item.height;
// Resize UIComponent to same size as Video object.
uic.width = video.width;
uic.height = video.height;
panel.title = "framerate: " + item.framerate;
panel.visible = true;
trace(ObjectUtil.toString(item));
}
private function ns_onCuePoint(item:Object):void {
trace("cue");
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:VBox>
<mx:Panel id="panel" visible="false">
<mx:UIComponent id="uic" />
<mx:ControlBar>
<mx:Button label="Play/Pause" click="ns.togglePause();" />
<mx:Button label="Rewind" click="ns.seek(0); ns.pause();" />
</mx:ControlBar>
</mx:Panel>
</mx:VBox>
</s:Application>
Can anyone help?
<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" creationComplete="init();">
<fx:Script>
<![CDATA[
import flash.globalization.Collator;
import mx.utils.ObjectUtil;
private var nc:NetConnection;
private var ns:NetStream;
private var video:Video;
private var meta:Object;
private var videoURL:String = "Fleximagteaser.flv";
private var nc1:NetConnection;
private var ns1:NetStream;
private var video1:Video;
private var meta1:Object;
private function init():void {
//video1
nc = new NetConnection();
nc.connect("rtmp");
nc.client = this;
nc.addEventListener(NetStatusEvent.NET_STATUS,onConnectionStatus);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR,onErrorHandler);
nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
}
private function onConnectionStatus(event:NetStatusEvent):void
{
var nsClient:Object = {};
nsClient.onMetaData = ns_onMetaData;
nsClient.onCuePoint = ns_onCuePoint;
ns = new NetStream(nc);
ns.play("videourl");
ns.client = nsClient;
video = new Video();
video.attachNetStream(ns);
uic.addChild(video);
}
private function onErrorHandler(event:AsyncErrorEvent):void{}
private function onSecurityError(event:SecurityErrorEvent):void{}
private function ns_onMetaData(item:Object):void {
trace("meta");
meta = item;
// Resize Video object to same size as meta data.
video.width = item.width;
video.height = item.height;
// Resize UIComponent to same size as Video object.
uic.width = video.width;
uic.height = video.height;
panel.title = "framerate: " + item.framerate;
panel.visible = true;
trace(ObjectUtil.toString(item));
}
private function ns_onCuePoint(item:Object):void {
trace("cue");
}
public function onBWDone():void
{}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:VBox>
<mx:Panel id="panel" visible="false">
<mx:UIComponent id="uic" />
<mx:ControlBar>
<mx:Button label="Play/Pause" click="ns.togglePause();" />
<mx:Button label="Rewind" click="ns.seek(0); ns.pause();" />
</mx:ControlBar>
</mx:Panel>
</mx:VBox>

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()"/>