ActionScript 3: Can not Find Uploaded Files - actionscript-3

This is my first ActionScript 3 application. It is supposed to upload data to specific location, which should be the www root location - the location where upload.php resides.
After I run the ActionScript application, I can select the file and I can see that the data is being uploaded, but I can never find it.
Would you be so kind, please, and help me to understand what is going on, and how can I find the uploaded data? I checked both: temporary files location, and the target destination.
Here is the ActionScript code:
package {
import flash.display.Sprite;
import flash.events.*;
import flash.net.*;
import flash.text.*;
public class ch30ex2 extends Sprite {
protected var fileRef:FileReference;
protected var uploadButton:TestButton;
protected var tf:TextField;
protected const YOUR_UPLOAD_URL:String = "http://localhost/Saifa/www/upload.php";
public function ch30ex2() {
fileRef = new FileReference();
fileRef.addEventListener(Event.SELECT, selectHandler);
fileRef.addEventListener(Event.CANCEL, cancelHandler);
fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);
fileRef.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
fileRef.addEventListener(Event.COMPLETE, completeHandler);
var btn:TestButton;
btn = new TestButton(100, 25, "Browse...");
btn.addEventListener(MouseEvent.CLICK, function(event:Event):void {
fileRef.browse();
});
btn.x = btn.y = 20;
addChild(btn);
uploadButton = btn = new TestButton(100, 25, "Upload");
btn.addEventListener(MouseEvent.CLICK, function(event:Event):void {
fileRef.upload(new URLRequest(YOUR_UPLOAD_URL));
});
btn.x = 20; btn.y = 55;
addChild(btn);
tf = new TextField();
tf.defaultTextFormat = new TextFormat("_sans", 11, 0);
tf.multiline = tf.wordWrap = true;
tf.autoSize = TextFieldAutoSize.LEFT;
tf.width = 300; tf.x = 130; tf.y = 58;
addChild(tf);
cancelHandler(null);
}
protected function selectHandler(event:Event):void {
tf.text = fileRef.name;
uploadButton.mouseEnabled = uploadButton.tabEnabled = true;
uploadButton.alpha = 1;
}
protected function cancelHandler(event:Event):void {
tf.text = "";
uploadButton.mouseEnabled = uploadButton.tabEnabled = false;
uploadButton.alpha = 0.3;
}
protected function progressHandler(event:ProgressEvent):void {
tf.text = "Uploading " +
event.bytesLoaded + " / " + event.bytesTotal + "bytes ...";
}
protected function errorHandler(event:ErrorEvent):void {
tf.text = event.text;
}
protected function completeHandler(event:Event):void {
tf.text = "Upload complete!";
}
}
}
import flash.display.*;
import flash.text.*;
class TestButton extends Sprite {
public var label:TextField;
public function TestButton(w:Number, h:Number, labelText:String) {
graphics.lineStyle(0.5, 0, 0, true);
graphics.beginFill(0xa0a0a0);
graphics.drawRoundRect(0, 0, w, h, 8);
label = new TextField();
addChild(label);
label.defaultTextFormat = new TextFormat("_sans", 11, 0, true, false,
false, null, null, "center");
label.width = w;
label.height = h;
label.text = labelText;
label.y = (h - label.textHeight)/2 - 2;
buttonMode = true;
mouseChildren = false;
}
}
and here is the PHP code, which is supposed to copy the temporary uploaded file:
<?php
move_uploaded_file($_FILES[‘Filedata’][‘tmp_name’], ‘./‘.time().$_FILES[‘Filedata’][‘name’]);
?>
All the code is from ActionScript Bible book
I would kindly like to ask for the following:
What can be the possible sources of my problem?
Looks my code correct? It gets compiled by FlashBuilder without problems
How can I identify source of my issue?
If you would have an example of working ActionScript + PHP application, I would be happy to see it.
As I spend hours after hours trying various things and combinations, I hope somebody might have had similar problem. Thank you.

In your PHP statement, there's a weired quote ‘ instead of a simple quote '.
<?php
move_uploaded_file($_FILES['Filedata']['tmp_name'], './'.time().$_FILES['Filedata']['name']);
?>
I tried with this and it worked fine.
Also here's the MXML i used to test:
<?xml version="1.0" encoding="utf-8"?>
<s:Application
minHeight="600"
minWidth="955"
creationComplete="application1_creationCompleteHandler(event)"
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import spark.components.Button;
import spark.components.Label;
protected function application1_creationCompleteHandler(event:FlexEvent):void {
ch30ex2();
}
protected var fileRef:FileReference;
protected var uploadButton:Button;
protected var tf:Label;
protected const YOUR_UPLOAD_URL:String = "http://127.0.0.1/test/test.php";
public function ch30ex2():void {
fileRef = new FileReference();
fileRef.addEventListener(Event.SELECT, selectHandler);
fileRef.addEventListener(Event.CANCEL, cancelHandler);
fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);
fileRef.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
fileRef.addEventListener(Event.COMPLETE, completeHandler);
var btn:Button;
btn = new Button();
btn.label = "Browse...";
btn.addEventListener(MouseEvent.CLICK, function(event:Event):void {
fileRef.browse();
});
btn.x = btn.y = 20;
addElement(btn);
uploadButton = btn = new Button();
btn.label = "Upload";
btn.addEventListener(MouseEvent.CLICK, function(event:Event):void {
fileRef.upload(new URLRequest(YOUR_UPLOAD_URL));
});
btn.x = 20;
btn.y = 55;
addElement(btn);
tf = new Label();
tf.width = 300;
tf.x = 130;
tf.y = 58;
addElement(tf);
cancelHandler(null);
}
protected function selectHandler(event:Event):void {
tf.text = fileRef.name;
uploadButton.mouseEnabled = uploadButton.tabEnabled = true;
uploadButton.alpha = 1;
}
protected function cancelHandler(event:Event):void {
tf.text = "";
uploadButton.mouseEnabled = uploadButton.tabEnabled = false;
uploadButton.alpha = 0.3;
}
protected function progressHandler(event:ProgressEvent):void {
tf.text = "Uploading " + event.bytesLoaded + " / " + event.bytesTotal + "bytes ...";
}
protected function errorHandler(event:ErrorEvent):void {
tf.text = event.text;
}
protected function completeHandler(event:Event):void {
tf.text = "Upload complete!";
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Placer ici les éléments non visuels (services et objets de valeur, par exemple). -->
</fx:Declarations>
</s:Application>

Related

Flash Webcam Capture

I am trying to build AS3 web audio/video capture. I have successfully tried to display the webcam stream with the help of this great tutorial. The next step is how do i capture the video when the user starts recording. Below is my code:
// video stuff
private var camW:int = 300;
private var camH:int = 300;
private var video:Video;
// block stuff
private var rows:int = 3;
private var cols:int = 3;
private var blockW:int = camW/cols;
private var blockH:int = camH/rows;
private var pointArray:Array = new Array();
public function Main():void {
// Checks if camera is installed
if (Camera.names.length > 0) {
trace("User has at least one camera installed.");
var camera:Camera = Camera.getCamera();
camera.setMode(camW, camH, 30);
camera.addEventListener(StatusEvent.STATUS, statusHandler);
video = new Video(camW, camH);
video.attachCamera(camera);
initBlocks();
addEventListener(Event.ENTER_FRAME, updateBlocks);
}else {
trace("User has no cameras installed.");
var text:TextField = new TextField();
text.text = "Device Not Found! Please check if the camera is installed.";
text.x = 20;
text.y = 20;
text.width = 500;
addChild(text);
}
function statusHandler(event:StatusEvent):void {
// This event gets dispatched when the user clicks the "Allow" or "Deny"
// button in the Flash Player Settings dialog box.
trace(event.code); // "Camera.Muted" or "Camera.Unmuted"
switch (event.code) {
case "Camera.Muted":
trace("User clicked Deny.");
var text:TextField = new TextField();
text.text = "Device Denied Permission! Please provide permission to record video!";
text.x = 20;
text.y = 20;
text.width = 500;
addChild(text);
break;
case "Camera.Unmuted":
trace("User clicked Accept.");
break;
}
}
}
private function initBlocks():void {
for (var r:int = 0; r < rows; r++) {
for (var c:int = 0; c < cols; c++) {
var newBlock:Sprite = new Sprite();
newBlock.name = "block" + r + c;
var p:Point = new Point(c * blockW, r * blockH);
newBlock.x = c * (blockW) + 20;
newBlock.y = r * (blockH) + 20;
pointArray[newBlock.name] = p;
var bmpd:BitmapData = new BitmapData(blockW, blockH);
var bmp:Bitmap = new Bitmap(bmpd);
bmp.name = "myBmp";
newBlock.addChild(bmp);
addChild(newBlock);
}
}
}
private function updateBlocks(e:Event):void {
var srcBmpd:BitmapData = new BitmapData(camW, camH);
srcBmpd.draw(video);
for (var r:int = 0; r < rows; r++) {
for (var c:int = 0; c < cols; c++) {
var b_mc:Sprite = this.getChildByName("block" + r + c) as Sprite;
var bmp:Bitmap = b_mc.getChildByName("myBmp") as Bitmap;
var p:Point = pointArray[b_mc.name];
bmp.bitmapData.copyPixels(srcBmpd, new Rectangle(p.x, p.y, blockW, blockH), new Point());
}
}
}
I am completely new to AS3, just started 2 days ago. What is the logic for audio/video capture in AS3? Any pointers/demo/tutorials/books appreciated
I had a very difficult time getting to work on the flash webcam recording. And as couple of posts here ( this one ) suggested to use some kind of flash servers like the Adobe Flash Server / Red5 Server. I did the same. I installed Red5 Server ( Please make sure you use the right JRE for the server to run smoothly after installation - as i had problems installing the demos ) and used Flex with FlashDevelop IDE ( Use Flex 3 Project to create a new project ). Here's below working sample code:
Main.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script source="Main.as"/>
<mx:VideoDisplay width="300" height="300" autoPlay="true" creationComplete="initCamera()" id="video"></mx:VideoDisplay>
<mx:Button label="Record" click="startRecording()" />
<mx:Button label="Stop" click="stopRecording()" />
</mx:Application>
Main.as
/**
* ...
* #author VishwaKumar
*/
import flash.events.NetStatusEvent;
import flash.media.Microphone;
import flash.net.NetConnection;
import flash.net.NetStream;
import mx.controls.Alert;
import flash.media.Camera;
import flash.media.Video;
import flash.display.Sprite;
public var camera:Camera;
public var nc:NetConnection;
public var ns:NetStream;
public var mic:Microphone;
public function initCamera():void {
var camW:int = 300;
var camH:int = 300;
if (Camera.names.length > 0) {
camera = Camera.getCamera();
camera.setMode(camW, camH, 30);
video.attachCamera(camera);
mic = Microphone.getMicrophone();
}else {
Alert.show("Device Not Found! Please check if the camera is installed.","Hardware Error!");
}
}
public function startRecording():void {
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
nc.connect("rtmp://127.0.0.1/oflaDemo");
}
public function netStatusHandler(event:NetStatusEvent):void {
trace(event.info.code);
switch(event.info.code) {
case "NetConnection.Connect.Success":
ns = new NetStream(nc);
ns.publish("test","record");
ns.attachAudio(mic);
ns.attachCamera(camera);
break;
default :
Alert.show("NetConnection.Connect.error");
break;
}
}
public function stopRecording():void {
ns.close();
}

How to stablish a Flash Peer-To-Peer Communication Over LAN (Without Cirrus/Stratus) with AIR

I'm trying to stream audio/video (I'm really only interested in Audio) in a LAN.
I've followed tutorials in internet which I've found very informative like the ones from Tom Krcha and thought would solve my problem. But until now I've not been successful in receiving the stream.
This is the code I'm using, can someone please point me out what am I missing?
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.media.Camera;
import flash.media.Microphone;
import flash.media.Video;
import flash.net.GroupSpecifier;
import flash.net.NetConnection;
import flash.net.NetGroup;
import flash.net.NetStream;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
[SWF(width="640", height="920", frameRate="60")]
public class LoudApp extends Sprite {
private var _interpreterStartButton:TextField = new TextField();
private var _listenerStartButton:TextField = new TextField();
private var _connectedLabel:TextField = new TextField();
private var _userTextField:TextField = new TextField();
private var _stream:NetStream;
private var _netConnection:NetConnection;
private var _netGroup:NetGroup;
private var _isConnected:Boolean;
private var _listenerStream:NetStream;
private var _isListener:Boolean;
private var _video:Video;
public function LoudApp() {
addEventListener(Event.ADDED_TO_STAGE, init, false, 0, true);
}
private function connect():void{
_netConnection = new NetConnection();
_netConnection.addEventListener(NetStatusEvent.NET_STATUS,netStatus);
_netConnection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
_netConnection.connect("rtmfp:");
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function init(event:Event):void {
_listenerStartButton.border = _interpreterStartButton.border = true;
_listenerStartButton.backgroundColor = _interpreterStartButton.borderColor = 0;
_listenerStartButton.autoSize = _interpreterStartButton.autoSize = TextFieldAutoSize.LEFT;
_listenerStartButton.selectable = _interpreterStartButton.selectable = false;
_connectedLabel = new TextField();
_connectedLabel.y = 70;
_connectedLabel.text = "not connected";
_listenerStartButton.addEventListener(MouseEvent.CLICK, onButtonClicked, false, 0, true);
_interpreterStartButton.addEventListener(MouseEvent.CLICK, onButtonClicked, false, 0, true);
_interpreterStartButton.text = " Start\rTalking! ";
_listenerStartButton.text = " Start\rListening! ";
addChild(_interpreterStartButton);
addChild(_listenerStartButton);
addChild(_connectedLabel);
_listenerStartButton.x = 120;
var textFormat:TextFormat = new TextFormat(null, 30, 0x000000, true);
_listenerStartButton.setTextFormat(textFormat);
_interpreterStartButton.setTextFormat(textFormat);
// Init the Video
_video = new Video(stage.stageWidth, stage.stageHeight - 100);
_video.y = 100;
addChild(_video);
connect();
}
private function onButtonClicked(event:MouseEvent):void {
_isListener = event.target == _listenerStartButton;
_listenerStartButton.removeEventListener(MouseEvent.CLICK, onButtonClicked);
_interpreterStartButton.removeEventListener(MouseEvent.CLICK, onButtonClicked);
removeChild(_listenerStartButton) && removeChild(_interpreterStartButton);
/*_isConnected && */setupStream();
}
private function setupStream():void{
var groupSpecifier:GroupSpecifier = new GroupSpecifier("en-GB");
groupSpecifier.serverChannelEnabled = true;
groupSpecifier.multicastEnabled = true;
groupSpecifier.ipMulticastMemberUpdatesEnabled = true;
groupSpecifier.addIPMulticastAddress("225.225.0.1:30303");
// _netGroup = new NetGroup(_netConnection, groupSpecifier.groupspecWithAuthorizations());
// _netGroup.addEventListener(NetStatusEvent.NET_STATUS, netStatus);
_stream = new NetStream(_netConnection, groupSpecifier.groupspecWithAuthorizations());
_stream.addEventListener(NetStatusEvent.NET_STATUS, netStatus);
if(_isListener){
_video.attachNetStream(_stream);
_stream.receiveAudio(true);
// _stream.receiveVideo(false);
_stream.play('sound');
return;
}else{
if(!Microphone.isSupported) return;
_stream.attachAudio(Microphone.getMicrophone());
// var camera:Camera = Camera.getCamera();
// _stream.attachCamera(camera);
_stream.publish("sound", "live");
// _video.attachCamera(camera);
}
}
private function netStatus(event:NetStatusEvent):void{
switch(event.info.code){
case "NetConnection.Connect.Success":
// _isConnected = true;
// _connectedLabel.text = "CONNECTED !";
break;
case "NetGroup.Connect.Success":
_isConnected = true;
_connectedLabel.text = "CONNECTED !";
break;
case "NetStream.Connect.Success":
break;
case "NetStream.Publish.Start":
break;
}
}
private function set listenerStream(value:NetStream):void {
_listenerStream = value;
}
}
}
Thank you in forward.
I was pointed out by Tom Krcha that some networks block multicast. And it was in deed the case.
I got a fresh router to test the apps again and it all worked perfectly.

Webcam shows mirror image using action script

Using Flash CS5.5 and action script 3 I have made a small application for image capturing through web cam and integrated it in php page working perfect also save image. But problem is it shows MIRROR image on screen means if I move my right hand on screen it shows left hand. My query is how can I correct this setting. Here is the code -
package take_picture_fla
{
import com.adobe.images.*;
import flash.display.*;
import flash.events.*;
import flash.media.*;
import flash.net.*;
import flash.ui.*;
import flash.utils.*;
dynamic public class MainTimeline extends MovieClip
{
public var capture_mc:MovieClip;
public var bitmap:Bitmap;
public var rightClickMenu:ContextMenu;
public var snd:Sound;
public var video:Video;
public var bitmapData:BitmapData;
public var warn:MovieClip;
public var save_mc:MovieClip;
public var bandwidth:int;
public var copyright:ContextMenuItem;
public var cam:Camera;
public var quality:int;
public function MainTimeline()
{
addFrameScript(0, frame1);
return;
}// end function
public function onSaveJPG(event:Event) : void
{
var myEncoder:JPGEncoder;
var byteArray:ByteArray;
var header:URLRequestHeader;
var saveJPG:URLRequest;
var urlLoader:URLLoader;
var sendComplete:Function;
var e:* = event;
sendComplete = function (event:Event) : void
{
warn.visible = true;
addChild(warn);
warn.addEventListener(MouseEvent.MOUSE_DOWN, warnDown);
warn.buttonMode = true;
return;
}// end function
;
myEncoder = new JPGEncoder(100);
byteArray = myEncoder.encode(bitmapData);
header = new URLRequestHeader("Content-type", "application/octet-stream");
saveJPG = new URLRequest("save.php");
saveJPG.requestHeaders.push(header);
saveJPG.method = URLRequestMethod.POST;
saveJPG.data = byteArray;
urlLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, sendComplete);
urlLoader.load(saveJPG);
return;
}// end function
public function warnDown(event:MouseEvent) : void
{
navigateToURL(new URLRequest("images/"), "_blank");
warn.visible = false;
return;
}// end function
function frame1()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
rightClickMenu = new ContextMenu();
copyright = new ContextMenuItem("Developed By www.webinfopedia.com Go to Application");
copyright.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, myLink);
copyright.separatorBefore = false;
rightClickMenu.hideBuiltInItems();
rightClickMenu.customItems.push(copyright);
this.contextMenu = rightClickMenu;
snd = new camerasound();
bandwidth = 0;
quality = 100;
cam = Camera.getCamera();
cam.setQuality(bandwidth, quality);
cam.setMode(320, 240, 30, false);
video = new Video();
video.attachCamera(cam);
video.x = 20;
video.y = 20;
addChild(video);
bitmapData = new BitmapData(video.width, video.height);
bitmap = new Bitmap(bitmapData);
bitmap.x = 360;
bitmap.y = 20;
addChild(bitmap);
capture_mc.buttonMode = true;
capture_mc.addEventListener(MouseEvent.CLICK, captureImage);
save_mc.alpha = 0.5;
warn.visible = false;
return;
}// end function
public function captureImage(event:MouseEvent) : void
{
snd.play();
bitmapData.draw(video);
save_mc.buttonMode = true;
save_mc.addEventListener(MouseEvent.CLICK, onSaveJPG);
save_mc.alpha = 1;
return;
}// end function
public function myLink(event:Event)
{
navigateToURL(new URLRequest("http://www.webinfopedia.com/export-database-data-to-excel-in-php.html"), "_blank");
return;
}// end function
}
}
You can just use video.scaleX = -1; to mirror the image.
You should check your camera's settings at the system level - it is possible that the device driver is set to mirror the image.

How can I play a RTMP video through netConnection and netStream

I am working on a prototype in which I have to play a video through RTMP protocol. My code is following :
private function init():void
{
streamID:String = "mp4:myVideo";
videoURL = "rtmp://fms.xstream.dk/*********.mp4";
vid = new video();
vid.width = 480;
vid.height = 320;
nc = new NetConnection();
nc.client = {onBWDone: function():void
{
}};
nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
nc.connect(videoURL);
}
private function onConnectionStatus(e:NetStatusEvent):void
{
if (e.info.code == "NetConnection.Connect.Success")
{
trace("Creating NetStream");
netStreamObj = new NetStream(nc);
netStreamObj.client = new CustomClient();
netStreamObj.play(streamID);
vid.attachNetStream(netStreamObj);
addChild(vid);
intervalID = setInterval(playback, 1000);
}
}
private function playback():void
{
trace((++counter) + " Buffer length: " + netStreamObj.bufferLength);
}
class CustomClient
{
public function onMetaData(info:Object):void
{
trace("metadata: duration=" + info.duration + " width=" + info.width + " height=" + info.height + " framerate=" + info.framerate);
}
public function onCuePoint(info:Object):void
{
trace("cuepoint: time=" + info.time + " name=" + info.name + " type=" + info.type);
}
}
But it not playing, not occurring any error and not plying, If anyone have any idea, please help me.
doing it this way worked for me. I just used a link to a news channel as example so try replacing it with your own stream url. (ps: ignore the pixelation, it's a low-res example link).
Also.. first you had a typo whereby you said vid = new video(); (meant = new Video??). Could that be an issue for the addChild(vid) line further on? Second you need functions like the asyncErrorHandler, onFCSubscribe and onBWDone that I've included when working with RTMP to stop errors that some streams throw out (in my past experiences anyway). This example code goes in a document class called RTMP_test.as (rename as preferred)...
package {
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.media.*;
import flash.system.*;
import flash.utils.ByteArray;
public class RTMP_test extends MovieClip
{
public var netStreamObj:NetStream;
public var nc:NetConnection;
public var vid:Video;
public var streamID:String;
public var videoURL:String;
public var metaListener:Object;
public function RTMP_test ()
{ init_RTMP(); }
function init_RTMP():void
{
/*
streamID = "mp4:myVideo";
videoURL = "rtmp://fms.xstream.dk/*********.mp4";
*/
streamID = "QVCLive1#14308";
videoURL = "rtmp://cp79650.live.edgefcs.net/live/";
vid = new Video(); //typo! was "vid = new video();"
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
nc.client = { onBWDone: function():void{} };
nc.connect(videoURL);
}
private function onConnectionStatus(e:NetStatusEvent):void
{
if (e.info.code == "NetConnection.Connect.Success")
{
trace("Creating NetStream");
netStreamObj = new NetStream(nc);
metaListener = new Object();
metaListener.onMetaData = received_Meta;
netStreamObj.client = metaListener;
netStreamObj.play(streamID);
vid.attachNetStream(netStreamObj);
addChild(vid);
//intervalID = setInterval(playback, 1000);
}
}
private function playback():void
{
//trace((++counter) + " Buffer length: " + netStreamObj.bufferLength);
}
public function asyncErrorHandler(event:AsyncErrorEvent):void
{ trace("asyncErrorHandler.." + "\r"); }
public function onFCSubscribe(info:Object):void
{ trace("onFCSubscribe - succesful"); }
public function onBWDone(...rest):void
{
var p_bw:Number;
if (rest.length > 0)
{ p_bw = rest[0]; }
trace("bandwidth = " + p_bw + " Kbps.");
}
function received_Meta (data:Object):void
{
var _stageW:int = stage.stageWidth;
var _stageH:int = stage.stageHeight;
var _videoW:int;
var _videoH:int;
var _aspectH:int;
var Aspect_num:Number; //should be an "int" but that gives blank picture with sound
Aspect_num = data.width / data.height;
//Aspect ratio calculated here..
_videoW = _stageW;
_videoH = _videoW / Aspect_num;
_aspectH = (_stageH - _videoH) / 2;
vid.x = 0;
vid.y = _aspectH;
vid.width = _videoW;
vid.height = _videoH;
}
} //end class
} //end package
UPDATED CODE:
New demo link: Now QVC (UK shopping) instead of Russia Today (World News).
Added line: nc.client = { onBWDone: function():void{} }; (since Flash Player is now more strict. Before it worked fine without this line).
Perhaps a more complete version of the code is like this. it should play RT channel live.
package {
import flash.events.NetStatusEvent;
import flash.events.AsyncErrorEvent;
import flash.display.MovieClip;
import flash.net.NetStream;
import flash.net.NetConnection;
import flash.media.Video;
import flash.utils.setInterval;
public class RTMP_test extends MovieClip {
public var netStreamObj:NetStream;
public var nc:NetConnection;
public var vid:Video;
public var streamID:String;
public var videoURL:String;
public var metaListener:Object;
public var intervalID:uint;
public var counter:int;
public function RTMP_test ()
{ init_RTMP(); }
function init_RTMP():void
{
streamID = "RT_2";
videoURL = "rtmp://fms5.visionip.tv/live/RT_2";
vid = new Video(); //typo! was "vid = new video();"
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
nc.connect(videoURL);
}
private function onConnectionStatus(e:NetStatusEvent):void
{
if (e.info.code == "NetConnection.Connect.Success")
{
trace("Creating NetStream");
netStreamObj = new NetStream(nc);
metaListener = new Object();
metaListener.onMetaData = received_Meta;
netStreamObj.client = metaListener;
netStreamObj.play(streamID);
vid.attachNetStream(netStreamObj);
addChild(vid);
intervalID = setInterval(playback, 1000);
}
}
private function playback():void
{
trace((++counter) + " Buffer length: " + netStreamObj.bufferLength);
}
public function asyncErrorHandler(event:AsyncErrorEvent):void
{ trace("asyncErrorHandler.." + "\r"); }
public function onFCSubscribe(info:Object):void
{ trace("onFCSubscribe - succesful"); }
public function onBWDone(...rest):void
{
var p_bw:Number;
if (rest.length > 0)
{ p_bw = rest[0]; }
trace("bandwidth = " + p_bw + " Kbps.");
}
function received_Meta (data:Object):void
{
var _stageW:int = stage.stageWidth;
var _stageH:int = stage.stageHeight;
var _aspectH:int;
var _videoW:int;
var _videoH:int;
var relationship:Number;
relationship = data.height / data.width;
//Aspect ratio calculated here..
_videoW = _stageW;
_videoH = _videoW * relationship;
_aspectH = (_stageH - _videoH) / 2;
vid.x = 0;
vid.y = _aspectH;
vid.width = _videoW;
vid.height = _videoH;
}
}
}

Is it possible to add the (.as) actionscript file dynamically in flex?

Am developing application in flex which is loaded the action script file .
<DrawingArea id="drawingArea" xmlns="*" width="100%" height="100%" add="drawingArea_addHandler(event)"/>
i need to add it dynamically,how to do this ?guide me
update
This is my Drawing area how to create var da:DrawingArea=new DrawingArea
how to access the listener function?
public function DrawingArea()
{
super();
addEventListener(FlexEvent.CREATION_COMPLETE, function(event:FlexEvent):void {
erase();
});
addEventListener(MouseEvent.MOUSE_DOWN, function(event:MouseEvent):void {
x1 = mouseX;
y1 = mouseY;
isDrawing = true;
});
addEventListener(MouseEvent.MOUSE_MOVE, function(event:MouseEvent):void {
if (!event.buttonDown)
{
isDrawing = false;
}
x2 = mouseX;
y2 = mouseY;
if (isDrawing)
{
graphics.lineStyle(2, drawColor);
graphics.moveTo(x1, y1);
graphics.lineTo(x2, y2);
x1 = x2;
y1 = y2;
}
});
addEventListener(MouseEvent.MOUSE_UP, function(event:MouseEvent):void {
isDrawing = false;
});
}
I have made changes to your code.
package
{
import flash.events.MouseEvent;
import mx.core.UIComponent;
public class DrawingArea
{
private var _target:UIComponent;
private var _x1:Number;
private var _y1:Number;
private var _x2:Number;
private var _y2:Number;
[Bindable]
private var _isDrawing:Boolean = false;
private var _drawColor:uint = 0xFFFF00
public function DrawingArea(target:UIComponent)
{
//TODO: implement function
_target = target
_target.addEventListener(MouseEvent.MOUSE_DOWN, downEvent, false, 0, true);
_target.addEventListener(MouseEvent.MOUSE_UP, upEvent, false, 0, true);
_target.addEventListener(MouseEvent.MOUSE_OUT, upEvent, false, 0, true);
}
private function downEvent(event:MouseEvent):void
{
_x1 = event.localX;
_y1 = event.localY;
_isDrawing = true;
_target.addEventListener(MouseEvent.MOUSE_MOVE, moveEvent, false, 0, true);
}
private function moveEvent(event:MouseEvent):void
{
if (!event.buttonDown)
{
_isDrawing = false;
}
_x2 = event.localX;
_y2 = event.localY;
if (_isDrawing)
{
_target.graphics.lineStyle(2, _drawColor);
_target.graphics.moveTo(_x1, _y1);
_target.graphics.lineTo(_x2, _y2);
_x1 = _x2;
_y1 = _y2;
}
}
private function upEvent(event:MouseEvent):void
{
_isDrawing = false;
_target.removeEventListener(MouseEvent.MOUSE_MOVE, moveEvent);
}
public function set drawColor(value:uint): void{
_drawColor = value;
}
}
}
Created a class DrawingAreaView.mxml in which, created object for DrawingArea and passed the class itself as container.
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns="components.*" xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="onInit();">
<mx:Script>
<![CDATA[
import components.DrawingArea;
private var drawingArea:DrawingArea;
private function onInit():void {
drawingArea = new DrawingArea(this);
}
]]>
</mx:Script>
</mx:Canvas>
Use above class in Application.
<DrawingAreaView id="drawingArea" width="100%" height="100%"/>
or
private var _drawingAreaView:DrawingAreaView = new DrawingAreaView();
parentObject.addChild(_drawingAreaView);
You will not be able to load a file in memory and then execute it, if that is what you want, in Acionscript. However, what you can do is create a DrawingArea (or any other element) at run-time based on some event (such as user click or a specific timeout period).
In this case your functions are defined inline. Till you dont give them names it will be impossible anyway.
i would suggest
addEventListener(MouseEvent.MOUSE_DOWN, mouseDownFunction);
public function mouseDownFunction(event:MouseEvent = null ):void {
x1 = mouseX;
y1 = mouseY;
isDrawing = true;
}
Then they should become accesable via the object. DrawingArea.mouseDownFunction()