I want to have embed video in flash game and have it looped. Is there a way to do it? As my code or more likely .seek or .resume dont give any effect? Am I using wrong commands or?
[Embed(source = "fast.flv", mimeType = "application/octet-stream")]
public var bytes:Class;
public var vidNS:NetStream
public var video:Video = new Video(1280, 720);
public var ns:NetStream;
public function Main() {
Doit();
}
private function Doit():void{
addChild(video);
var vidNC:NetConnection = new NetConnection(); vidNC.connect(null);
vidNS = new NetStream(vidNC);
var metaListener :Object = new Object(); metaListener = { onMetaData: process_Metadata };
vidNS.client = metaListener;
vidNS.addEventListener(NetStatusEvent.NET_STATUS, videoStatusHandler);
vidNS.play(null);
var file:ByteArray = new bytes();
vidNS.appendBytes(file);
video.attachNetStream(vidNS);
}
function process_Metadata (in_Data :Object):void
{
trace("duration is : " + in_Data.duration );
}
function videoStatusHandler (event:NetStatusEvent):void
{
if (event.info.code == "NetStream.Buffer.Empty")
{
trace('loop')
vidNS.seek(0); vidNS.resume();
}
}
You can loop by just simply re-feeding the bytes to the decoder (NetStream)
It's possible that you also need to involve the option RESET_BEGIN:
yourNS.appendBytesAction( NetStreamAppendBytesAction.RESET_BEGIN );
Try setting your code like below:
[Embed(source = "fast.flv", mimeType = "application/octet-stream")]
public var bytes:Class;
public var vidNS:NetStream;
public var video:Video = new Video(1280, 720);
public var ns:NetStream;
//# declare these vars outside of a function for global access
public var file:ByteArray = new bytes();
public var vidNC:NetConnection;
public var metaListener :Object;
public function Main()
{
Doit();
}
private function Doit():void
{
addChild(video);
vidNC = new NetConnection(); vidNC.connect(null);
vidNS = new NetStream(vidNC);
metaListener new Object(); metaListener = { onMetaData: process_Metadata };
vidNS.client = metaListener;
vidNS.addEventListener(NetStatusEvent.NET_STATUS, videoStatusHandler);
vidNS.play(null);
//var file:ByteArray = new bytes();
vidNS.appendBytes(file); //# feed video bytes to decoder
video.attachNetStream(vidNS);
}
function process_Metadata (in_Data :Object):void
{
trace("duration is : " + in_Data.duration );
}
function videoStatusHandler (event:NetStatusEvent):void
{
if (event.info.code == "NetStream.Buffer.Empty")
{
trace('now doing: looping...')
//# there is no timeline ".seek" in appendBytes mode, use ".seek" to clear the buffer for a new re-feed
vidNS.seek(0); //clears the current buffer (video data is removed)
vidNS.appendBytesAction( NetStreamAppendBytesAction.RESET_BEGIN ); //re-set timestamps for decoder
vidNS.appendBytes(file); //re-feed video bytes to decoder
}
}
So Thanks to VC. One i ended up with this code:
[Embed(source="1.flv", mimeType="application/octet-stream")]
public var bytes:Class;
public var vidNS:NetStream;
public var video:Video = new Video(1280, 720);
public var file:ByteArray = new bytes();
public var vidNC:NetConnection;
public var metaListener :Object;
public function Main()
{
Doit();
}
private function Doit():void
{
addChild(video);
vidNC = new NetConnection(); vidNC.connect(null);
vidNS = new NetStream(vidNC);
metaListener new Object(); metaListener = { onMetaData: process_Metadata };
vidNS.client = metaListener;
vidNS.play(null);
vidNS.appendBytes(file);
video.attachNetStream(vidNS);
}
function process_Metadata (in_Data :Object):void
{
trace("loop ");
vidNS.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
vidNS.appendBytes(file);
}
Its working like it should, but i'm not sure if thats the right way of doing it ^^.
Related
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);
}
}
}
My flash project has specific task to show the dynamic gallery items based on an XML list and there is a download option available for each gallery item.
For this I made a movieclip (imageTile) with a Thumbnail, Title, ProgressBar & ProgressText as shown below.
I have two classes named Main.as and FileRef.as
Main.as
var tileMap:Dictionary = new Dictionary();
public var tile:ImageTile;
addChild(wall);
wallWidth = wall.width;
wallHeight = wall.height;
var columns:Number;
var my_x:Number;
var my_y:Number;
var my_thumb_width:Number;
var my_thumb_height:Number;
var images:XMLList;
var total:Number;
var swipe:Number = 0;
var myXMLLoader:URLLoader = new URLLoader();
myXMLLoader.load(new URLRequest("gallery.xml"));
myXMLLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
images = myXML.IMAGE;
total = images.length();
myXMLLoader.removeEventListener(Event.COMPLETE, processXML);
myXMLLoader = null;
var loader:Loader;
for (var i:uint = 0; i < total; i++) {
tile = new ImageTile();
wall.addChild(tile);
tile.x = i % 3 * 400 + 180;
tile.y = Math.floor(i / 3) * 650 + 250;
var imageName:String = images[i].#FULL;
path = images[i].#Path;
var title:String = images[i].#Title;
**var caption:TextField = tile.getChildByName("caption_tf") as TextField;**
caption.text = title;
tile.addEventListener(MouseEvent.CLICK, onTileClick(path));
loader = new Loader();
loader.load(new URLRequest("images/" + imageName));
tileMap[loader] = tile;
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoad);
}
//trace(myXML);
}
var tileMap:Dictionary = new Dictionary();
function onImageLoad(e:Event):void {
var loader:Loader = e.target.loader;
var tile:ImageTile = tileMap[loader] as ImageTile;
var image:Bitmap = loader.content as Bitmap;
image.x = -100;
image.y = -100;
image.width=366;
image.height=418;
var textField:DisplayObject = tile.getChildByName("caption_tf");
var textFieldDepth:int = tile.getChildIndex(textField);
tile.addChildAt(image, textFieldDepth);
tileMap[loader] = null;
image.smoothing = true;
}
function onTileClick(url:String):Function {
return function(me:MouseEvent):void {
path = url;
var download:FileRef = new FileRef();
download.downloadFile(path);
}
FileRef.as code
public var mc_loaded : MovieClip = Main.gameInstance.tile.getChildByName("mc_loaded") as MovieClip,
mc_progress : MovieClip = Main.gameInstance.tile.getChildByName("mc_progress") as MovieClip,
txt_prog : TextField = Main.gameInstance.tile.getChildByName("txt_prog") as TextField;
public function downloadFile(url:String) : void
{
/// Download the gallery item codes using url
}
public function progressHandler( event : ProgressEvent ) : void
{
//mc_loaded.scaleX = (event.bytesLoaded / event.bytesTotal) ;
}
public function completeHandler( event : Event ) : void
{
//reset progress bar after download is finished
mc_loaded.scaleX = 0; // I want to use the imageTile element
txt_prog.text = "download finished";
}
public function OnZipComplete(evt:flash.events.Event):void
{
txt_prog.text = "download finished";
}
The download works fine, but I can not get the progress bar and progress text for every tile created.
I got the answer
Remove onTileClick(url:String) function from Main.as
Main.as
function processXML(e:Event):void {
//// Codes /////
//// Codes /////
var download:FileRefTut = new FileRefTut();
tile.addEventListener(MouseEvent.CLICK, download.downloadFile(path));
}
FileRef.as
public var txt_prog:TextField, mc_loaded:MovieClip;
public function downloadFile(url:String):Function {
return function(me:MouseEvent):void {
var tile:ImageTile = me.currentTarget as ImageTile;
txt_prog = tile.getChildByName("txt_prog") as TextField;
mc_loaded = tile.getChildByName("mc_loaded") as MovieClip;
}
public function progressHandler( event : ProgressEvent ) : void
{
mc_loaded.scaleX = (event.bytesLoaded / event.bytesTotal) ;
}
public function completeHandler( event : Event ) : void
{
//reset progress bar after download is finished
mc_loaded.scaleX = 0; // I want to use the imageTile element
txt_prog.text = "download finished";
}
public function OnZipComplete(evt:flash.events.Event):void
{
txt_prog.text = "download finished";
}
I have this code in my MXML project, I want to get dynamic Stream connection for different and dynamic usernames.
private var inStream:NetStream;
private function listenStream(user:String):void
{
this["inStream"+user] = new NetStream(connection);
this["inStream"+user].play(user);
}
private function closeStream(user:String):void
{
//clear stream listener
this["inStream"+user].close();
}
But this code is not worked, How can i build dynamic object names in ActionScript3?
Thanks alot
Try Dictionary
import flash.utils.Dictionary
private var streamDict:Dictionary = new Dictionary();
private function listenStream(user:String):void
{
var key:String = getKey(user);
var lastStream:NetStream = streamDict[key] as NetStream;
if (lastStream)
{
//close the last stream or do sth else
}
else
{
streamDict[key] = new NetStream(connection);
streamDict[key].play(user);
}
}
private function closeStream(user:String):void
{
var key:String = getKey(user);
//clear stream listener
var stream:NetStream = streamDict[key] as NetStream ;
if (stream)
{
stream.close();
}
//delete the stream
streamDict[key] = null;
delete streamDict[key];
}
private function getKey(user:String):String
{
return "inStream" + user;
}
Im trying to add minimizable panel in Flex. Is it possible? any ideas guys ?
you can take some idea from the following link:-
http://flexscript.wordpress.com/2008/08/28/flex-minimize-maximize-panel-component/
I digged an old app I had developed in Flex 3. This was how I minimized an Application.
Hope it helps!
private var trayIcon:BitmapData;
//onCreation of App
public function initApp(event:Event):void
{
loadTrayIcon();
this.addEventListener(Event.CLOSING, minToTray);
}
private function minToTray(event:Event):void{
event.preventDefault();
dock();
}
public function loadTrayIcon():void
{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, readyToTray);
loader.load(new URLRequest("assets/circleblack.PNG"));
}
public function dock():void{
stage.nativeWindow.visible = false;
NativeApplication.nativeApplication.icon.bitmaps = [trayIcon];
}
private function closeApp(event:Event):void{
stage.nativeWindow.close();
}
public function unDock(event:Event):void{
stage.nativeWindow.visible = true;
stage.nativeWindow.orderToFront();
NativeApplication.nativeApplication.icon.bitmaps = [];
}
public function readyToTray(event:Event):void{
trayIcon = event.target.content.bitmapData;
var myMenu:NativeMenu = new NativeMenu();
var openItem:NativeMenuItem = new NativeMenuItem("Open");
var closeItem:NativeMenuItem = new NativeMenuItem("Close");
openItem.addEventListener(Event.SELECT, unDock);
closeItem.addEventListener(Event.SELECT, closeApp);
myMenu.addItem(openItem);
myMenu.addItem(new NativeMenuItem("", true));
myMenu.addItem(closeItem);
this.systemTrayIconMenu
if(NativeApplication.supportsSystemTrayIcon){
SystemTrayIcon(NativeApplication.nativeApplication.icon).tooltip = "Test App";
SystemTrayIcon(NativeApplication.nativeApplication.icon).
addEventListener(MouseEvent.CLICK, unDock);
stage.nativeWindow.addEventListener(
NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, winMinimized);
SystemTrayIcon(NativeApplication.nativeApplication.icon).menu = myMenu;
this.nativeApplication.menu = myMenu;
}
}
private function winMinimized(displayStateEvent:NativeWindowDisplayStateEvent):void{
if(displayStateEvent.afterDisplayState == NativeWindowDisplayState.MINIMIZED){
displayStateEvent.preventDefault();
dock();
}
}
I can't add name and image from Facebook contacts to SqLite, becouse adding is inside in loop and loader start when Event is Complete. Fllowing code adds data to the database, but in the name of the object is the last person out of the loop. Any thoughts? Thanks!
private var person:PersonVO;
protected function handleFriendsLoad(response:Object, fail:Object):void
{
if (fail) { return }
var friends:Array = response as Array;
var l:uint=friends.length;
for (var i:uint=0;i<l;i++) {
var friend:Object = friends[i];
FacebookDesktop.api('/'+friend.id, loadData);
}
}
private function loadData(object:Object, fail:Object):void
{
if (fail) { return; }
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageToByteArray);
loader.load(new URLRequest(FacebookDesktop.getImageUrl(object.id, 'large')));
person = new PersonVO()
person.name = object.first_name;
}
private function imageToByteArray(event:Event):void
{
var wczytaj:Loader = (event.target as LoaderInfo).loader;
var image:Bitmap = Bitmap(wczytaj.content);
var encoderJpeg:JPEGEncoder = new JPEGEncoder();
var byteArray:ByteArray = encoderJpeg.encode(image.bitmapData);
person.image= byteArray;
insert(person);
}
private function insert(person:PersonVO):void
{
dbStatement.text = "INSERT INTO person (name,image) values(:name,:jpeg)";
dbStatement.parameters[":name"] = person.name;
dbStatement.parameters[":jpeg"] = person.image;
dbStatement.execute();
}
Extend Loader class functionality:
dynamic class DynamicLoader extends Loader{}
Then store whatever you want in instances of DynamicLoader:
private function loadData(object:Object, fail:Object):void
{
if (fail) { return; }
var person:PersonVO = new PersonVO();
person.name = object.first_name;
var loader:DynamicLoader = new DynamicLoader();
loader.person = person;
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageToByteArray);
loader.load(new URLRequest(FacebookDesktop.getImageUrl(object.id, 'large')));
}
private function imageToByteArray(event:Event):void
{
var wczytaj:DynamicLoader = (event.target as LoaderInfo).loader as DynamicLoader;
var image:Bitmap = Bitmap(wczytaj.content);
var encoderJpeg:JPEGEncoder = new JPEGEncoder();
var byteArray:ByteArray = encoderJpeg.encode(image.bitmapData);
var person:PersonVO = wczytaj.person;
person.image= byteArray;
insert(person);
}
I have not used private var person:PersonVO;. So if you are not using it in the other methods of your class, you could remove it completely.