Duplicating video Stream Actionscript 3 - actionscript-3

Good Morning,
i am working on a video class, using a CRTMP Server for streaming. This works fine, but for my solution i need to duplicate the video stream (for some effects).
I googled for duplicate MovieClips and tried to duplicate the video like this.
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.media.*;
import flash.system.*;
import flash.utils.ByteArray;
public class Main extends MovieClip
{
public var netStreamObj:NetStream;
public var nc:NetConnection;
public var vid:Video;
public var vid2:Video;
public var streamID:String;
public var videoURL:String;
public var metaListener:Object;
public function Main()
{
init_RTMP();
}
private function init_RTMP():void
{
streamID = "szene3.f4v";
videoURL = "rtmp://213.136.73.230/maya";
vid = new Video(); //typo! was "vid = new video();"
vid2 = 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);
//vid2.attachNetStream(netStreamObj); // wont work
addChild(vid);
// addChild(vid2); // wont work either
//intervalID = setInterval(playback, 1000);
}
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
trace("asyncErrorHandler.." + "\r");
}
private 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;
vid2.x = 0;
vid2.y = _aspectH ;
}
}
It should be possible to duplicate the video stream. 2 Instance of the same videoStream. What am i doing wrong ?
Thanks for help.

"This means that i have to double the netstream. This is not what i want."
"I tried to duplicate the video per Bitmap.clone. But i got an sandbox violation."
You can try the workaround suggested here: Netstream Play(null) Bitmapdata Workaround
I'll show a quick demo of how it can be applied to your code.
This demo code assumes your canvas is width=550 & height=400. Keep that ratio if scaling up.
package
{
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.media.*;
import flash.system.*;
import flash.utils.ByteArray;
import flash.geom.*;
import flash.filters.ColorMatrixFilter;
public class Main 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 vid1_sprite : Sprite = new Sprite();
public var vid2_sprite : Sprite = new Sprite();
public var vid2_BMP : Bitmap;
public var vid2_BMD : BitmapData;
public var colMtx:Array = new Array(); //for ColorMatrix effects
public var CMfilter:ColorMatrixFilter;
public function Main()
{
init_RTMP();
}
private function init_RTMP():void
{
streamID = "szene3.f4v";
videoURL = "rtmp://213.136.73.230/maya";
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(null); //for file playback
nc.connect(videoURL); //for RTMP streams
}
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("vid.flv"); //if File
netStreamObj.play(streamID); //if RTMP
vid.attachNetStream(netStreamObj);
}
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
trace("asyncErrorHandler.." + "\r");
}
private function received_Meta(data:Object):void
{
trace("Getting metadata");
var _stageW:int = stage.stageWidth;
var _stageH:int = stage.stageHeight;
var _videoW:int = data.width;
var _videoH:int = data.height;
var _aspectH:int = 0;
var Aspect_num:Number;
Aspect_num = data.width / data.height;
//Aspect ratio calculated here..
_videoW = _stageW;
_videoH = _videoW / Aspect_num;
_aspectH = (_stageH - _videoH) / 2;
trace("_videoW : " + _videoW);
trace("_videoW : " + _videoH);
trace("_aspectH : " + _aspectH);
vid.x = 0;
vid.y = 0;
vid.width = _videoW;
vid.height = _videoH;
setup_Copy(); //# Do this after video resize
}
public function setup_Copy () : void
{
vid2_BMD = new BitmapData(vid.width, vid.height, false, 0);
vid2_BMP = new Bitmap( vid2_BMD );
vid1_sprite.addChild(vid);
vid1_sprite.x = 0;
vid1_sprite.y = 0;
addChild( vid1_sprite );
vid2_sprite.addChild( vid2_BMP );
vid2_sprite.x = 0;
vid2_sprite.y = vid.height + 5;
addChild( vid2_sprite );
stage.addEventListener(Event.ENTER_FRAME, draw_Video);
}
public function draw_Video (evt:Event) : void
{
if ( netStreamObj.client.decodedFrames == netStreamObj.decodedFrames ) { return; } // Here we skip multiple readings
//# Get bitmapdata directly from container of video
if ( vid1_sprite.graphics.readGraphicsData().length > 0 )
{
vid2_BMD = GraphicsBitmapFill(vid1_sprite.graphics.readGraphicsData()[0]).bitmapData;
}
effect_BitmapData(); //# Do an effect to bitmapdata
}
public function effect_BitmapData ( ) : void
{
//# Matrix for Black & White effect
colMtx = colMtx.concat([1/3, 1/3, 1/3, 0, 0]); // red
colMtx = colMtx.concat([1/3, 1/3, 1/3, 0, 0]); // green
colMtx = colMtx.concat([1/3, 1/3, 1/3, 0, 0]); // blue
colMtx = colMtx.concat([0, 0, 0, 1, 0]); // alpha
CMfilter = new ColorMatrixFilter(colMtx);
vid2_BMP.bitmapData.applyFilter(vid2_BMD, new Rectangle(0, 0, vid.width, vid.height), new Point(0, 0), CMfilter);
}
}
}

Related

Stage dimensions in a new NativeWindow

i'm building a flash desktop App where the user clicks on a button and opens a SWF file (a game) in a new window, i used a NativeWindow to achieve it, i did the folowing:
var windowOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
windowOptions.systemChrome = NativeWindowSystemChrome.STANDARD;
windowOptions.type = NativeWindowType.NORMAL;
var newWindow:NativeWindow = new NativeWindow(windowOptions);
newWindow.stage.scaleMode = StageScaleMode.NO_SCALE;
newWindow.stage.align = StageAlign.TOP_LEFT;
newWindow.bounds = new Rectangle(100, 100, 2000, 800);
newWindow.activate();
var aLoader:Loader = new Loader;
aLoader.load(new URLRequest(path));
newWindow.stage.addChild(aLoader);
the result is this:
the game doesn't take the whole space available. When i change the "NO_SCALE" to "EXACT_FIT":
newWindow.stage.scaleMode = StageScaleMode.EXACT_FIT;
i got this:
it only shows the top-left corner of the game. I also tried "SHOW_ALL" and "NO_BORDER". I got the same result as "EXACT_FIT".
When i open the SWF file of the game separatly it's displayed normally:
any idea how can i display the SWF game as the image above?
The best solution for that is to have the dimensions of your external game in pixel. you have to stretch the loader to fit it in your stage. if you are try to load different games with different sizes to your stage, save the swf dimensions with their URL addresses.
var extSWFW:Number = 550;
var extSWFH:Number = 400;
var extURL:String = "./Data/someSwf.swf";
var mainStageWidth:Number = 1024;
var mainStageHeight:Nubmer = 768;
var aLoader:Loader = new Loader;
aLoader.load(new URLRequest(extURL));
newWindow.stage.addChild(aLoader);
aLoader.scaleY = aLoader.scaleX = Math.min(mainStageWidth/extSWFW,mainStageHeight/extSWFH);
It is not very difficult to figure dimensions of a loaded SWF because it is engraved into it's header, you can read and parse it upon loading. Here's the working sample:
package assortie
{
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import flash.utils.ByteArray;
public class Dimensions extends Sprite
{
private var loader:Loader;
public function Dimensions()
{
super();
loader = new Loader;
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
loader.load(new URLRequest("outer.swf"));
}
private function onLoaded(e:Event):void
{
var aBytes:ByteArray = loader.contentLoaderInfo.bytes;
var aRect:Rectangle = new Rectangle;
var aRead:BitReader = new BitReader(aBytes, 8);
var perEntry:uint = aRead.readUnsigned(5);
aRect.left = aRead.readSigned(perEntry) / 20;
aRect.right = aRead.readSigned(perEntry) / 20;
aRect.top = aRead.readSigned(perEntry) / 20;
aRect.bottom = aRead.readSigned(perEntry) / 20;
aRead.dispose();
aRead = null;
trace(aRect);
}
}
}
import flash.utils.ByteArray;
internal class BitReader
{
private var bytes:ByteArray;
private var position:int;
private var bits:String;
public function BitReader(source:ByteArray, start:int)
{
bits = "";
bytes = source;
position = start;
}
public function readSigned(length:int):int
{
var aSign:int = (readBits(1) == "1")? -1: 1;
return aSign * int(readUnsigned(length - 1));
}
public function readUnsigned(length:int):uint
{
return parseInt(readBits(length), 2);
}
private function readBits(length:int):String
{
while (length > bits.length) readAhead();
var result:String = bits.substr(0, length);
bits = bits.substr(length);
return result;
}
static private const Z:String = "00000000";
private function readAhead():void
{
var wasBits:String = bits;
var aByte:String = bytes[position].toString(2);
bits += Z.substr(aByte.length) + aByte;
position++;
}
public function dispose():void
{
bits = null;
bytes = null;
}
}

Simplebutton image is larger than it actually is

I'm creating a button I use beginBitmapFill method to add image to it. Everything works normally, the problem is that the image loaded by a Loader () is greater than it actually is
Class that creates the button
package mode {
import flash.display.Sprite;
import org.osmf.net.StreamingURLResource;
public class LoadButton extends Sprite
{
public var Save;
public function LoadButton(x:uint,save:String,url:String)
{
var button:CustomSimpleButton = new CustomSimpleButton(url);
button.x = x;
Save = save;
addChild(button);
}
}
}
import flash.display.*;
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Shape;
import flash.display.SimpleButton;
import flash.events.*;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.net.URLRequest;
import flash.geom.Matrix;
class CustomSimpleButton extends SimpleButton
{
private var upColor:uint = 0xFFCC00;
private var overColor:uint = 0xCCFF00;
private var downColor:uint = 0x00CCFF;
private var sizew:uint = 100;
private var sizeh:uint = 88;
public function CustomSimpleButton(url:String)
{
downState = new ButtonDisplayState(downColor, sizew,sizeh,url);
overState = new ButtonDisplayState(overColor, sizew,sizeh,url);
upState = new ButtonDisplayState(upColor, sizew,sizeh,url);
hitTestState = new ButtonDisplayState(upColor, sizew * 2,sizeh,url);
hitTestState.x = -(sizew / 4);
hitTestState.y = hitTestState.x;
useHandCursor = true;
}
}
class ButtonDisplayState extends Shape
{
private var bgColor:uint;
private var size:uint;
private var sizeh:uint;
public function ButtonDisplayState(bgColor:uint, sizew:uint,sizeh:uint,url:String)
{
this.bgColor = bgColor;
this.size = sizew;
this.sizeh = sizeh;
draw(url);
}
private function draw(url:String):void
{
var myLoader:Loader = new Loader();
var image:Bitmap;
var uri = new URLRequest(url);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event)
{
image = new Bitmap(e.target.content.bitmapData);
graphics.beginBitmapFill(image.bitmapData);
graphics.drawRect(0, 0, 100, 88);
graphics.endFill();
});
myLoader.load(uri);
}
}
How the image is 100x88
as it is
The reason it is showing up cropped like that, is because the BitmapData is larger than the area you are filling.
Before filling the shape with the loaded BitmapData, you need to sale it down to the appropriate size.
Based on the answer to this question, you could do the following:
var scaleAmount:Number;
if(e.target.content.width >= e.target.content.height){
scaleAmount = size / e.target.content.width;
}else{
scaleAmount = sizeh / e.target.content.height;
}
var scaledBitmapData:BitmapData = scaleBitmapData(e.target.content.bitmapData, scaleAmount);
graphics.beginBitmapFill(scaledBitmapData);
graphics.drawRect(0, 0, size, sizeh);
graphics.endFill();
function scaleBitmapData(bitmapData:BitmapData, scale:Number):BitmapData {
scale = Math.abs(scale);
var width:int = (bitmapData.width * scale) || 1;
var height:int = (bitmapData.height * scale) || 1;
var transparent:Boolean = bitmapData.transparent;
var result:BitmapData = new BitmapData(width, height, transparent);
var matrix:Matrix = new Matrix();
matrix.scale(scale, scale);
result.draw(bitmapData, matrix);
return result;
}
It might be easier though, to just make your button state a Sprite and add the loaded Bitmap object and scale it directly:
class ButtonDisplayState extends Sprite
{
private var bgColor:uint;
private var image:Bitmap;
private var size:uint;
private var sizeh:uint;
public function ButtonDisplayState(bgColor:uint, sizew:uint,sizeh:uint,url:String)
{
this.bgColor = bgColor;
this.size = sizew;
this.sizeh = sizeh;
loadImage(url);
}
private function loadImage(url:String):void
{
var myLoader:Loader = new Loader();
var uri = new URLRequest(url);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event)
{
image = new Bitmap(e.target.content.bitmapData);
//scale the bitmap while retaining aspect ratio
//scale based off which dimension (width or height) is bigger
if(image.width >= image.height){
image.scaleX= size / image.width; //scale it to the width specified
image.scaleY = image.scaleX; //make the height aspect ratio match the widths
}else{
image.scaleY = sizeh /image.height;
image.scaleX = image.scaleY;
}
addChild(image); //add it to the display list of this object
});
myLoader.load(uri);
}
}

ActionScript 3 Apparently I cannot access movieclip

I've created a zoom function but when I try to scale the bg_image nothing happends. It is like I cannot access it's properties. Does anyone know why? :)
Ty!
Main class
package
{
import flash.display.MovieClip;
import flash.utils.Dictionary;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.text.TextField;
import fl.controls.Button;
import fl.controls.List;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.display.Shape;
import fl.transitions.Fly;
import fl.motion.MatrixTransformer;
import flash.events.KeyboardEvent;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.ui.Mouse;
public class Main extends Sprite
{
// Zoom
public static var scale:Number = 1;
public var spImage:Sprite;
public var mat:Matrix;
public var mcIn:MovieClip;
public var mcOut:MovieClip;
public var boardWidth:int = 980;
public var boardHeight:int = 661;
public var boardMask:Shape;
public var externalCenter:Point;
public var internalCenter:Point;
public const scaleFactor:Number = 0.8;
public var minScale:Number = 0.25;
public var maxScale:Number = 10.0;
// ------------------------
// Grafikk
public var bg_image:Sprite;
//-------------------------------
//-----------------------------------------------
public var routeArray:Array;
public var startList:List = new List();
public var sluttList:List = new List();
public var S_Norway:Dictionary = new Dictionary();
public var S_Australia:Dictionary = new Dictionary();
public var S_China:Dictionary = new Dictionary();
public var S_South_Africa:Dictionary = new Dictionary();
public var S_Brazil:Dictionary = new Dictionary();
public var S_USA:Dictionary = new Dictionary();
public var S_France:Dictionary = new Dictionary();
// ------------------------------------------------------
public static var airportDict:Dictionary = new Dictionary();
public function Main()
{
addEventListener(Event.ADDED_TO_STAGE, init);
// ---------------------------------
}
public function init(e:Event):void
{
bg_image = new Image(0, 0);
this.addChild(bg_image);
bg_image.addEventListener(MouseEvent.CLICK, mouseCoordinates);
removeEventListener(Event.ADDED_TO_STAGE, init);
// Zoom
this.graphics.beginFill(0xB6DCF4);
this.graphics.drawRect(0,0,boardWidth,boardHeight);
this.graphics.endFill();
spImage = new Sprite();
this.addChild(spImage);
boardMask = new Shape();
boardMask.graphics.beginFill(0xDDDDDD);
boardMask.graphics.drawRect(0,0,boardWidth,boardHeight);
boardMask.graphics.endFill();
boardMask.x = 0;
boardMask.y = 0;
this.addChild(boardMask);
spImage.mask = boardMask;
minScale = boardWidth / bg_image.width;
mcIn = new InCursorClip();
mcOut = new OutCursorClip();
bg_image.addChild(mcIn);
bg_image.addChild(mcOut);
bg_image.scaleX = minScale;
bg_image.scaleY = minScale;
spImage.addChild(bg_image);
spImage.addChild(mcIn);
spImage.addChild(mcOut);
spImage.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
spImage.addEventListener(MouseEvent.CLICK, zoom);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
S_USA["x"] = 180.7;
S_USA["y"] = 149.9;
S_USA["bynavn"] = "New York";
S_Norway["x"] = 423.7;
S_Norway["y"] = 76.4;
S_Norway["bynavn"] = "Oslo";
S_South_Africa["x"] = -26;
S_South_Africa["y"] = 146;
S_South_Africa["bynavn"] = "Cape Town";
S_Brazil["x"] = 226;
S_Brazil["y"] = 431.95;
S_Brazil["bynavn"] = "Rio de Janeiro";
S_France["x"] = 459.1;
S_France["y"] = 403.9;
S_France["bynavn"] = "Paris";
S_China["x"] = 716.2;
S_China["y"] = 143.3;
S_China["bynavn"] = "Beijing";
S_Australia["x"] = 809.35;
S_Australia["y"] = 414.95;
S_Australia["bynavn"] = "Sydney";
// ----------------------------------------------------
airportDict["USA"] = S_USA;
airportDict["Norway"] = S_Norway;
airportDict["South Africa"] = S_South_Africa;
airportDict["Brazil"] = S_Brazil;
airportDict["France"] = S_France;
airportDict["China"] = S_China;
airportDict["Australia"] = S_Australia;
for (var k:Object in airportDict)
{
var value = airportDict[k];
var key = k;
startList.addItem({label:key, data:key});
sluttList.addItem({label:key, data:key});
var airport:Airport = new Airport(key,airportDict[key]["bynavn"]);
airport.koordinater(airportDict[key]["x"], airportDict[key]["y"]);
bg_image.addChild(airport);
}
// --------------------------------------------
// --------------------------------------------
// -----------------------------------------------
}
private function startDragging(mev:MouseEvent):void
{
spImage.startDrag();
}
private function stopDragging(mev:MouseEvent):void
{
spImage.stopDrag();
}
private function zoom(mev:MouseEvent):void
{
if ((!mev.shiftKey)&&(!mev.ctrlKey))
{
return;
}
if ((mev.shiftKey)&&(mev.ctrlKey))
{
return;
}
externalCenter = new Point(spImage.mouseX,spImage.mouseY);
internalCenter = new Point(bg_image.mouseX,bg_image.mouseY);
if (mev.shiftKey)
{
bg_image.scaleX = Math.max(scaleFactor*bg_image.scaleX, minScale);
bg_image.scaleY = Math.max(scaleFactor*bg_image.scaleY, minScale);
}
if (mev.ctrlKey)
{
trace("Minscale: ", maxScale)
trace("Returned: ", 1/scaleFactor*bg_image.scaleY)
bg_image.scaleX = Math.min(1/scaleFactor*bg_image.scaleX, maxScale);
bg_image.scaleY = Math.min(1/scaleFactor*bg_image.scaleY, maxScale);
}
mat = this.transform.matrix.clone();
MatrixTransformer.matchInternalPointWithExternal(mat,internalCenter,externalCenter);
bg_image.transform.matrix = mat;
}
private function keyHandler(ke:KeyboardEvent):void
{
mcIn.x = spImage.mouseX;
mcIn.y = spImage.mouseY;
mcOut.x = spImage.mouseX;
mcOut.y = spImage.mouseY;
mcIn.visible = ke.ctrlKey;
mcOut.visible = ke.shiftKey;
if (ke.ctrlKey || ke.shiftKey)
{
Mouse.hide();
}
else
{
Mouse.show();
}
}
private function reise(evt:MouseEvent):void
{
var new_flight:Flight = new Flight(airportDict[startList.selectedItem.label]["x"],airportDict[startList.selectedItem.label]["y"],airportDict[sluttList.selectedItem.label]["x"],airportDict[sluttList.selectedItem.label]["y"]);
bg_image.addChild(new_flight);
}
private function mouseCoordinates(event: MouseEvent):void
{
// these are the x and y relative to the object
var localMouseX:Number = bg_image.mouseX;
var localMouseY:Number = bg_image.mouseY;
trace("Local coordinates: ", localMouseX, localMouseY);
// these are the x and y relative to the whole stage
var stageMouseX:Number = event.stageX;
var stageMouseY:Number = event.stageY;
trace("Global coordinates: ", stageMouseX, stageMouseY);
}
}
}
Image class:
package {
import flash.display.Sprite;
import flash.display.MovieClip;
public class Image extends Sprite
{
public function Image(y_:Number, x_:Number)
{
this.y = y_
this.x = x_
}
}
}
You don't have minScale declared, neither maxScale.
bg_image should be declared as Sprite, otherwise Compiler Error: Implicit coercion...
`
public var bg_image:Sprite;
As your image is very small, you may want to add your listener to the stage, and not the image, it would be very dificult to click in such a small image.
Also, here is your example working with MOUSE_WHEEL, instead of Click + Ctrl / Shift
stage.addEventListener(MouseEvent.MOUSE_WHEEL, zoom);
private function zoom(mev:MouseEvent):void
{
mev.delta > 0 ?
bg_image.scaleX = bg_image.scaleY = Math.max(scaleFactor * bg_image.scaleX, minScale) :
bg_image.scaleX = bg_image.scaleY = Math.min(1/scaleFactor * bg_image.scaleX, maxScale) ;
}

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