Destroy camera in as3 - actionscript-3

I am using the Camera on Flash, but when I finish to use, now can I "destroy" the camera object for improve the application performance?
private var camera_atual:Camera = Camera.getCamera();
private var video_camera:Video = new Video(820, 546);
camera_atual.setQuality(0,100);
camera_atual.setMode(550,480,30,true);
video_camera.attachCamera(camera_atual);
this.palco_mc.addChild(video_camera);

See Video.attachCamera() - "To drop the connection to the Video object, pass null."
The camera itself should be destroyed manually :)

Related

How to pause and restart a NetStream object?

I have a NetStream object, based upon the following code:
streamID = "mystreamkey";
videoURL = "rtmp://mystreamurl";
vid = new Video();
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
nc.client = { onBWDone: function():void{}, streamConnected: streamConnected, streamDisconnected: streamDisconnected };
nc.connect(videoURL);
...
metaListener = new Object();
metaListener.onMetaData = received_Meta;
netStreamObj.client = metaListener;
netStreamObj.play(streamID);
vid.attachNetStream(netStreamObj);
addChild(vid);
All this is working fine, and I can also use netStreamObj.pause() to pause the live stream.
But how do I restart it? netStreamObj.play() won't work - it requires one parameter, so then I wrote this:
netStreamObj.play(streamID);
vid.attachNetStream(netStreamObj);
But this isn't working either.
How do I restart the stream, so that it connects to the live stream it was previously connected to?
How do I restart the stream, so that it connects to the live stream it
was previously connected to?
For future reference, check the NetStream API documentation for options. You'll be looking to check out the commands listed under the Public methods section.
You can use either :
resume(): Resumes playback of a video stream that is paused.
usage : netStreamObj.resume();
togglePause(): Pauses or resumes playback of a stream.
usage : netStreamObj.togglePause();
I suggest using togglePausesince it auto-detects the playback state of the NetStream object. Your "Pause" button (or MovieClip) should simply have a click listener event whose function has this line : netStreamObj.togglePause();. It's that easy...

Getting Bitmap from Video decoded with Nestream AppendBytes (AS3)?

I am wondering if someone who has handled NetStream.appendBytes in Flash knows how to get the bitmapData from a decoded video frame? I have already looked at this question but that is from 3 years ago and the more recent comment/answer seems to be gone. In 2014 has anyone managed to turn those bytes into a bitmap? I am working with Flash Player 11.8 and this is not a desktop/AIR app.
In the image below I can do steps 1) and 2) but there's a brick wall at step 3)
The problem is that simply using bitmapdata.draw(video_container); does not work but instead it throws a Policy File error even though I am using a byteArray (from local video file in the same directory as the SWF). No internet is even involved but Flash tells me that "No Policy File granted permission from the server" or such nonsense. I think the error is just a bail-out insteading of straight up saying "You are not allowed to do this.."
I have tried: trying to appease this Crossdomain.xml issue anyway and looking into all known security/domain settings. I came to the conclusion that the error is not the problem but a side effect of the issue.. The issue here being that: Flash Player is aware of the SWF's location and of any files local to it. That's okay when you pass a String as URL etc but when the Netstream data is not local to the SWF domain then it becomes a Policy File issue. Problem is my data is in the Memory not in a folder like the SWF and therefore cannot alllow bitmapData.draw since it cannot "police" an array of bytes, any known fixes for this?... (I can't even say the words I really wanted to use).
What I am trying to achieve: Is to essentially use Netstream as an H.263 or H.264 image decoder in the same way Loader is a JPEG-to-Bitmap decoder or LoadCompressed.. is an MP3-to-PCM decoder. You know, access the raw material (here RGB pixels), apply some effects functions and then send to screen or save to disk.
I know it is a little late, but I think I found a solution for your problem.
So, to avoid the Security sandbox violation #2123 Error, you have just to do like this :
// ...
net_stream.play(null);
net_stream.play('');
// ...
Hope that can help.
I know this question is a couple months old, but I wanted to post the correct answer (because I just had this problem as well and other will too).
Correct answer:
It's a bug that has been open at adobe for almost 2 years
Link to the bug on Adobe
Work Around until the bug gets fixed (I am using this and it works great):
Workaround using Sprite and graphics
To take a snapshot from a video stream we don't need NetStream.appendBytes which inject data into a NetStream object.
For that we can use BitmapData.draw which has some security constraints. That's why in many times we get a flash security error. About that, Adobe said :
"... This method is supported over RTMP in Flash Player 9.0.115.0 and later and in Adobe AIR. You can control access to streams on Flash Media Server in a server-side script. For more information, see the Client.audioSampleAccess and Client.videoSampleAccess properties in Server-Side ActionScript Language Reference for Adobe Flash Media Server. If the source object and (in the case of a Sprite or MovieClip object) all of its child objects do not come from the same domain as the caller, or are not in a content that is accessible to the caller by having called the Security.allowDomain() method, a call to the draw() throws a SecurityError exception. This restriction does not apply to AIR content in the application security sandbox. ...".
For crossdomain file creation and some other security config for AMS server, you can take a look on this post : Crossdomain Video Snapshot - Fixing BitmapData.draw() Security Sandbox Violation.
After allowing our script to get data from our video stream, we can pass to the code.
I wrote a code that play a video stream ( rtmp or http ) and take a snapshot to show it in the stage or save it as a file after applying a pixel effect :
const server:String = null; //'rtmp://localhost/vod'
const stream:String = 'stream'; // 'mp4:big_buck_bunny_480p_h264.mp4';
var nc:NetConnection;
var ns:NetStream;
var video:Video;
const jpg_quality:int = 80;
const px_size:int = 10;
nc = new NetConnection();
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, function(e:AsyncErrorEvent):void{});
nc.addEventListener(NetStatusEvent.NET_STATUS, function(e:NetStatusEvent):void{
if(e.info.code == 'NetConnection.Connect.Success'){
ns = new NetStream(nc);
ns.addEventListener(NetStatusEvent.NET_STATUS, function(e:NetStatusEvent):void{});
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, function(e:AsyncErrorEvent):void{});
video = new Video(320, 180);
video.x = video.y = 10;
video.attachNetStream(ns);
addChild(video);
ns.play(stream);
}
})
nc.connect(server);
btn_show.addEventListener(
MouseEvent.CLICK,
function(e:MouseEvent): void{
var bmp:Bitmap = pixelate(video, px_size);
bmp.x = 10;
bmp.y = 220;
addChild(bmp);
}
)
btn_save.addEventListener(
MouseEvent.CLICK,
function(e:MouseEvent): void{
var bmp:Bitmap = pixelate(video, px_size);
var jpg_encoder:JPGEncoder = new JPGEncoder(80);
var jpg_stream:ByteArray = jpg_encoder.encode(bmp.bitmapData);
var file:FileReference = new FileReference();
file.save(jpg_stream, 'snapshot_'+int(ns.time)+'.jpg');
}
)
function pixelate(target:DisplayObject, px_size:uint):Bitmap {
var i:uint, j:uint = 0;
var s:uint = px_size;
var d:DisplayObject = target;
var w:uint = d.width;
var h:uint = d.height;
var bmd_src:BitmapData = new BitmapData(w, h);
bmd_src.draw(d);
var bmd_final:BitmapData = new BitmapData(w, h);
var rec:Rectangle = new Rectangle();
rec.width = rec.height = s;
for (i = 0; i < w; i += s){
for (j = 0; j < h; j += s){
rec.x = i;
rec.y = j;
bmd_final.fillRect(rec, bmd_src.getPixel32(i, j));
}
}
bmd_src.dispose();
bmd_src = null;
return new Bitmap(bmd_final);
}
Of course, this is just a simple example to show the manner to get a snapshot from a video stream, you should adapt and improve it to your needs ...
I hope all that can help you.

Error #1009: Cannot access a property or method of a null object reference.on camera

im working on augmented reality application where my augmented object can be touched by hands. So it has motion detection in it. i build it using flartoolkit and away3d.
I already made the augmented reality and motion detection part. The problem is where i combined them,
I get the class for motion detection from http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking
Whenever i try to run my program, it get Error #1009: Cannot access a property or method of a null object reference.on camera
from what i analyze, my code cant differentiate which camera that i use.
If anyone can show hot to fix it, it will help me a lot
here's initialization for camera in augmented reality part
this.flarManager.removeEventListener(Event.INIT, this.onFlarManagerInited);
this.camera3D = new FLARCamera_Away3D(this.flarManager, new Rectangle(0, 0, this.stage.stageWidth, this.stage.stageHeight));
this.view = new View3D({x:0.5*this.stage.stageWidth, y:0.5*this.stage.stageHeight, scene:this.scene3D, camera:this.camera3D});
this.addChild(this.view);
this.light = new DirectionalLight3D();
this.light.direction = new Vector3D(500, -300, 200);
this.scene3D.addLight(light);
and here's initialization for camera in my motion detection part
var camW : int = 420;
var camH : int = 320;
// Create the camera
var cam : Camera = Camera.getCamera();
cam.setMode(camW, camH, stage.frameRate);
// Create a video
var vid : Video = new Video(camW, camH);
vid.attachCamera(cam);

How to cache audio stream data and access it in AS3

I'm streaming an MP3 file in AS3. All is working fine (I can play it) but I'm looking to implement a 'seek' bar. This means I will need to cache the file (as it's being downloaded) and then access the cached data when the user seeks a specific time in the song.
The code to actually play the mp3 stream:
function openStream( stream )
{
var s:Sound = new Sound();
var req:URLRequest = new URLRequest(stream);
var context:SoundLoaderContext = new SoundLoaderContext(500, true);
s.load(req, context);
s.play();
}
So how would I cache the file as it's being downloaded and then access the data from the cache?
I know this is pretty far from a trivial task, so I would be grateful if you could even just provide a few links to some tutorials/docs/articles.
You do not need to cache the sound for this.
The downloaded sound data is is available as long as the sound object lives in memory.
So all you need to do is take the sound object outside the function into the class scope..
Also the play function returns the current SoundChannel used by the Sound.
private var snd:Sound = new Sound();
private var channel:SoundChannel;
function openStream( stream ) {
...
channel = snd.play();
}
To implement the seek functionality you may make use of,
bytesLoaded (To know how much of the sound is downloaded)
soundChannel.position (To know current sound position)

if I load a flv with netStream, how can I call a function when the flv stops playing

I have a website in ActionScript 3 that has lots of FLV animations that happen when you press buttons. Right now this is how I have it set up.
in AS3,
im loading FLv's (which are animations I exported in FLV form from After Effects)
with net stream. I have a timer set up for the same amount of length of time that the animations (FLV's) play and when the timer stops it calls a function that closes the stream, opens a new one and plays another video. The only problem I noticed using timers is that if the connection is slow and (animation)stops for a second, the timer keeps going, and calls the next flv too early.
Does anyone know a way to load a flv, or swf for that matter, at the end of play of the flv? so that the next FLV will always play at the end of the run time of the previous FLV, rather than using timers?
im thinking onComplete but I don't know how to implement that!?
Sequential playing is pretty easy to achieve with the OSMF framework, you should check it out. Google "osmf tutorials" and you should find a few tutorials online.
The framework is fairly recent, but it looks like it may become the de facto solution for media delivery in Flash as it's not limited to video but also audio & images.
As a developer you won't have to bother with the NetStream & NetConnection classes. Developing video solutions , as well as audio & images solutions should be streamlined and easier to handle. Only limitation is that it requires Flash 10
Here's some code for checking when a FLV ends with NetStream. I just provide snippets as I assume you got the FLV up and running already.
//create a netstream and pass in your connection
var netStream:NetStream = new NetStream(conn);
//add callback function for PlayStatus -event
var client : Object = {};
client.onPlayStatus = onPlayStatus;
netStream.client = client;
//attach your NetStream to the connection as usual
//---
//function that gets called onPlayStatus
function onPlayStatus(info : Object) : void {
trace("onPlayStatus:" +info.code + " " + info.duration);
if (info.code == "NetStream.Play.Complete") {
//play the next FLV and so on
}
}
EDIT: With your example code it will look something like this.
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
var listener:Object = new Object();
listener.onMetaData = function(md:Object):void{};
listener.onPlayStatus = function(info : Object) : void {
trace("onPlayStatus:" +info.code + " " + info.duration);
if (info.code == "NetStream.Play.Complete") {
//play the next FLV and so on
}
};
ns.client = listener;
vid1.attachNetStream(ns);
const moviename1:String = "moviename2.flv";
const moviename1:String = "moviename3.flv";
var movietoplay:String = "moviename.flv";
ns.play(movietoplay);