Linking a webcam in a flex application - apache-flex

i am having a very strange problem while linking a webcam i xperience following error
ArgumentError: Error #2126: NetConnection object must be connected.
at flash.net::NetStream/ctor()
at flash.net::NetStream()
Following is my code in main.mxml
<fx:Script>
<![CDATA[
import flash.media.Camera;
import flash.media.Video;
import flash.net.NetConnection;
import mx.core.UIComponent;
import com.kahaf.plutay.* ;
private var inVideo:Video;
private var outVideo:Video;
private var inVideoWrapper:UIComponent;
private var camera:Camera;
private var mic:Microphone;
private var inStream:NetStream;
private var outStream:NetStream;
private function defaultVideoMode(): void
{
VideoPanel.width = 726;
VideoPanel.height = 494;
inVideo.width = 726;
inVideo.height = 494;
}
private function showInComingVideo():void
{
inVideo = new Video(VideoPanel.width,VideoPanel.height);
inVideo.attachNetStream(inStream);
inVideoWrapper = new UIComponent();
inVideoWrapper.addChild(inVideo);
VideoPanel.addElement(inVideoWrapper);
defaultVideoMode();
}
private function setupVideo(event:MouseEvent): void
{
camera = Camera.getCamera();
mic = Microphone.getMicrophone();
mic.setLoopBack(false);
mic.setUseEchoSuppression(true);
camera.setMode(640,480,20);
camera.setQuality(65536,90);
var conn:NetConnection = Connection.getConnection().conn;
inStream = new NetStream(conn);
inStream.play(conn);
showInComingVideo();
}
]]>
<s:Group x="283" y="330" width="234" height="149" id="VideoPanel" >
</s:Group>
<s:Button x="447" y="151" label="Click Me." click="setupVideo(event)"/>
here is the code of my connection class :
import flash.net.NetConnection;
public class Connection extends NetConnection
{
public static var conObj:Connection;
public var conn:NetConnection;
public var target:Object;
public var selector:Function;
public function Connection()
{
conn = new NetConnection;
target = null;
selector = null;
conn.client = this;
}
public static function getConnection():Connection
{
if(conObj == null)
{
conObj = new Connection();
}
return conObj;
}
}

This the correct order when handling NetConnection and NetStreams:
Create and establish the NetConnection (NetConnection.connect())
Wait for the NetConnection.Connect.Success event (NetStatusEvent.NET_STATUS)
Create your NetStream and attach the connected NetConnection to it
Publish/play your stream

Related

could not be able set labelField of List Control in flex 4.6

I'm not able to set the Label of List Control which I first save to SQLite database and then show that as lebelField of List control my code is following :
List of Cities mxml is :
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="Cities"
>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import model.DataModel;
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
import mx.events.IndexChangedEvent;
import spark.components.SplitViewNavigator;
import spark.components.ViewNavigator;
import spark.transitions.ViewTransitionBase;
protected function myList_changeHandler():void {
// Create a reference to the SplitViewNavigator.
var splitNavigator:SplitViewNavigator = navigator.parentNavigator as SplitViewNavigator;
// Create a reference to the ViewNavigator for the Detail frame.
var detailNavigator:ViewNavigator = splitNavigator.getViewNavigatorAt(1) as ViewNavigator;
detailNavigator.transitionsEnabled = false;
// Change the view of the Detail frame based on the selected List item.
detailNavigator.pushView(DisplayContents, list_of_cities.selectedItem);
}
]]>
</fx:Script>
<s:VGroup width="100%" height="100%">
<s:List id="list_of_cities" height="100%" width="100%" change="myList_changeHandler();"
dataProvider="{DataModel.getInstance().cityList}">
</s:List>
</s:VGroup>
city value object is ::
package valueobject
{
[Bindable]
public class CityValueObject
{
public var id:uint;
public var nameofcity:String;
}}
and DataModel is ::
package model
{
import flash.data.SQLConnection;
import mx.collections.ArrayCollection;
[Bindable]
public class DataModel
{
public var connection:SQLConnection;
public var cityList:ArrayCollection = new ArrayCollection();
public var logs:String="Application Logs........\n";
public static var _instance:DataModel;
public static function getInstance():DataModel
{
if(_instance == null)
{
_instance = new DataModel();
}
return _instance;
}
}}
and CityUtilities class is:
package utillities
{
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import model.DataModel;
import mx.collections.Sort;
import mx.collections.SortField;
import valueobject.CityValueObject;
public class CityUtils
{
public static function getAllCities():void
{
var contactListStatement:SQLStatement = new SQLStatement();
contactListStatement.sqlConnection = DataModel.getInstance().connection;
contactListStatement.text = "SELECT * FROM CITYNAME";
contactListStatement.execute();
var result:SQLResult = contactListStatement.getResult();
if( result.data!=null)
{
DataModel.getInstance().cityList.removeAll();
for(var count:uint=0;count<result.data.length;count++)
{
var cityVO:CityValueObject = new CityValueObject();
cityVO.id = result.data[count].id;
cityVO.nameofcity = result.data[count].city;
DataModel.getInstance().cityList.addItem(cityVO);
}
}
sortData();
}
public static function sortData():void
{
var dataSortField:SortField = new SortField();
dataSortField.name = "nameofcity";
dataSortField.numeric = false;
/* Create the Sort object and add the SortField object created earlier to the array of fields to sort on. */
var numericDataSort:Sort = new Sort();
numericDataSort.fields = [dataSortField];
/* Set the ArrayCollection object's sort property to our custom sort, and refresh the ArrayCollection. */
DataModel.getInstance().cityList.sort = numericDataSort;
DataModel.getInstance().cityList.refresh();
}
public static function updateLog(newLog:String):void
{
DataModel.getInstance().logs += new Date().time+" :-> "+newLog+"\n";
}
}}
Please tell me how to set labelField according to SQLite nameofcity column thanks in advance
You need to display nameofcity means set LabelField property for spark list like following
<s:VGroup width="100%" height="100%">
<s:List id="list_of_cities" height="100%" width="100%" labelField="nameofcity" change="myList_changeHandler();"
dataProvider="{DataModel.getInstance().cityList}">
</s:List>
if it shows [object CityValueObject] then create custom ItemRenderer then override data method
override public function set data(value:Object):void
{
super.data = value;
var vo:CityValueObject=value as CityValueObject;
lblCityName.text = vo.nameofcity.toString();
}
All other code is correct, but mistake is that I placed
for(var count:uint=0;count<result.data.length;count++)
{
var cityVO:CityValueObject = new CityValueObject();
cityVO.id = result.data[count].id;
//cityVO.nameofcity = result.data[count].city; // Here I should Have written like
cityVO.nameofcity = result.data[count].nameofcity;// this works as I needed
DataModel.getInstance().cityList.addItem(cityVO);
}

SQLite in Flex Help

I am trying to get anytihng from my SQLite to render in Flex, and I can't figure out how to display any data, even text, in Flex. What am I doing wrong?
<fx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.filesystem.File;
import mx.collections.ArrayCollection;
private var conn:SQLConnection;
private var createStmt:SQLStatement;
private var selectStmt:SQLStatement;
[bindable] public var dataField:ArrayCollection;
[bindable] private var row:Object;
[bindable] private var pngIndex:int;
[bindable] public var pngTitle:String;
[bindable] private var pngByteArray:ByteArray;
[Bindable] private var dp:ArrayCollection = new ArrayCollection();
private function init():void
{
conn = new SQLConnection();
conn.addEventListener (SQLEvent.OPEN, openSuccess);
conn.addEventListener (SQLErrorEvent.ERROR, openFailure);
var dbFile:File = File.applicationDirectory.resolvePath("assets/NM.sqlite");
conn.openAsync(dbFile);
}
private function openSuccess(event:SQLEvent):void
{
conn.removeEventListener(SQLEvent.OPEN, openSuccess);
conn.removeEventListener(SQLErrorEvent.ERROR, openFailure);
getData();
}
private function getData():void
{
//status = "Loading data";
selectStmt = new SQLStatement();
selectStmt.sqlConnection = conn;
var sql:String = "SELECT Title FROM Data WHERE 'Index' = 0";
selectStmt.text = sql;
selectStmt.addEventListener(SQLEvent.RESULT, selectResult);
selectStmt.addEventListener(SQLErrorEvent.ERROR, selectError);
selectStmt.execute();
}
private function selectResult(event:SQLEvent):void
{
//status = "Data loaded";
selectStmt.removeEventListener(SQLEvent.RESULT, selectResult);
selectStmt.removeEventListener(SQLErrorEvent.ERROR, selectError);
[bindable] var result:SQLResult = selectStmt.getResult();
dataField = new ArrayCollection(result.data);
dp = ArrayCollection(dataField);
if (dataField != null) {
pngIndex = result.data.Index;
pngTitle = result.data.Title;
pngByteArray = result.data.Picture;
/* Pic.source = pngByteArray; */
}
}
]]>
</fx:Script>
<s:List x="31" y="44" width="511" height="415" dataProvider="{dp}"></s:List>
I've tried a number of different components, and I can't seem to get the data to bind properly (although this code finally doesn't have the dreaded "Data binding will not be able to detect assignments to... " message, or the other dreaded "Property undefined" message).
Please help!
Fixed.
<fx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.filesystem.File;
import mx.collections.ArrayCollection;
private var conn:SQLConnection;
private function init():void
{
conn = new SQLConnection();
conn.addEventListener(SQLEvent.OPEN, openSuccess);
conn.addEventListener(SQLErrorEvent.ERROR, openFailure);
var dbFile:File = File.applicationDirectory.resolvePath("assets/NM.sqlite");
conn.openAsync(dbFile);
}
private function openSuccess(event:SQLEvent):void
{
conn.removeEventListener(SQLEvent.OPEN, openSuccess);
conn.removeEventListener(SQLErrorEvent.ERROR, openFailure);
getData();
}
private function getData():void
{
var select:SQLStatement = new SQLStatement();
select.sqlConnection = conn;
select.text = "SELECT Title FROM Data WHERE 'Index' = 0";
select.addEventListener(SQLEvent.RESULT, selectResult);
select.addEventListener(SQLErrorEvent.ERROR, selectError);
select.execute();
}
private function selectResult(event:SQLEvent):void
{
var result:SQLResult = event.currentTarget.getResult();
if(result.data)
{
list.dataProvider = new ArrayCollection(result.data);
}
}
]]>
</fx:Script>
<s:List id="list" x="31" y="44" width="511" height="415" labelField="Title" />
I also recommend you read up more on how Flex works with lists and item renderers. There was a lot of problems with this code (ie. result.data.Index; is wrong since data is an array). From what I can gather, you'll want a custom item renderer. Furthermore, I don't recommend you use Binding if you don't need it (as with this example altogether) since it incurs extra resources.

Stop List From Scrolling

I have a datagrid that's using a custom itemrender with a button in it. I have a problem whereby when I click on a button the datagrid list scrolls its self. How can I prevent this behaviour?
Extended datagrid
<mx:DataGrid xmlns:mx="http://www.adobe.com/2006/mxml"
doubleClickEnabled="false"
alternatingItemColors="[#ffffff, #f1f1f1]"
mouseDown="mdhandler(event)"
sortableColumns="true"
xmlns:datagrids="components.content.contents.datagrids.*"
creationComplete="_creationcomplete(event)">
<mx:Script>
<![CDATA[
import mx.binding.utils.BindingUtils;
import components.preview.PreviewPlayEvent;
import mx.controls.Button;
import components.preview.PreviewPlay;
import components.content.contents.FixedHelp.FixedHelp;
import mx.events.FlexEvent;
import mx.core.Application;
import mx.events.ToolTipEvent;
import flash.utils.describeType;
import mx.utils.ObjectUtil;
import components.remix.PadDisplay.PadContent;
import components.remix.PadDisplay.PalletteCode;
import mx.core.IUIComponent;
import mx.controls.Image;
import mx.managers.DragManager;
import mx.core.DragSource;
import mx.events.DragEvent;
// Embed icon image.
[Embed(source='assets/proxy.png')]
public var dragImg:Class;
private var _scrollEnabled:Boolean=true;
private var _currentpath:String="";
public static const TYPE_ARRAY:Array=["loop", "one-shot sample", "stem", "track"]
private function _creationcomplete(e:FlexEvent=null):void
{
addEventListener(Event.ENTER_FRAME, enterframe, false, 0, true);
addEventListener(PreviewPlayEvent.PLAY, previewplayrequest, false, 0, true);
addEventListener(PreviewPlayEvent.STOP,previewstoprequest,false,0,true)
}
private function previewplayrequest(e:PreviewPlayEvent):void
{
_currentpath=e._path;
//Application.application.previewplay(e._path)
invalidateList();
}
private function previewstoprequest(e:PreviewPlayEvent):void
{
_currentpath="";
//Application.application.previewplay(e._path)
invalidateList();
}
public function get critera():String
{
return _currentpath;
}
public function set criteria(value:String):void
{
_currentpath=value;
}
private function enterframe(e:Event):void
{
if (Application.application.hashelp == false)
{
}
else
{
removeEventListener(Event.ENTER_FRAME, enterframe);
var xml:XML=Application.application.helpxml;
var fh:FixedHelp=Application.application.fixedhelp;
var helptext:String=Application.application.helpxml.studio.loops.text;
fh.addItem(helptext, this);
}
}
private function mdhandler(e:MouseEvent):void
{
describeType(e.currentTarget)
e.currentTarget.toString()
if (e.currentTarget.selectedItem != null && getQualifiedClassName(e.target) != "mx.controls::Button")
{
_scrollEnabled=false
var dragdata:XML=XML(e.currentTarget.selectedItem) as XML
var ds:DragSource=new DragSource()
var dragdataasObject:Object=ObjectUtil.copy(e.currentTarget.selectedItem)
ds.addData(dragdataasObject, PadContent.LOOP_FORMAT);
//trace(ds.dataForFormat(PadContent.LOOP_FORMAT)) // I expect xml data to trace out here but it does not
var imageproxy:Image=new Image();
imageproxy.source=dragImg;
imageproxy.height=40;
imageproxy.width=40;
DragManager.doDrag(this, ds, e, imageproxy, (this.x - e.stageX) + 40, (this.y - e.stageY) + 130)
this.selectedItem=null;
}
else
{
e.stopImmediatePropagation();
}
}
private function userLabelFunction(item:Object, column:DataGridColumn):String
{
var newstr:String=new String(item.t + "\n" + TYPE_ARRAY[item.ty])
return newstr;
}
private function catFunction(item:Object, column:DataGridColumn):String
{
var newstr:String=TYPE_ARRAY[item.ty];
return newstr;
}
private function bpmFunction(item:Object, column:DataGridColumn):int
{
var newstr:Number=new Number(item.bp);
return newstr;
}
private function beatCountFunction(item:Object, column:DataGridColumn):int
{
var newstr:int=new int(item.bc);
return newstr;
}
private function sortbpm(obj1:Object, obj2:Object):int
{
var valueA:Number=obj1.bp;
var valueB:Number=obj2.bp;
return ObjectUtil.numericCompare(valueA, valueB);
}
private function sortbeatcount(obj1:Object, obj2:Object):int
{
var valueA:Number=obj1.bc;
var valueB:Number=obj2.bc;
return ObjectUtil.numericCompare(valueA, valueB);
}
public function get scrollEnabled():Boolean
{
return _scrollEnabled;
}
public function set scrollEnabled(value:Boolean):void
{
_scrollEnabled=value;
}
override protected function dragScroll():void
{
if (_scrollEnabled)
{
super.dragScroll();
}
}
]]>
</mx:Script>
<mx:columns>
<mx:DataGridColumn dataField="r"
headerText=""
itemRenderer="components.content.contents.datagrids.ImageRendererLoops"/>
<mx:DataGridColumn dataField="t"
headerText="Title"
labelFunction="userLabelFunction"/>
<mx:DataGridColumn dataField="bc"
headerText="Beats"
labelFunction="beatCountFunction"
sortCompareFunction="sortbeatcount"/>
<mx:DataGridColumn dataField="BPM"
headerText="BPM"
labelFunction="bpmFunction"
sortCompareFunction="sortbpm"/>
<mx:DataGridColumn itemRenderer="components.preview.PreviewPlay"/>
</mx:columns>
</mx:DataGrid>
Item Renderer
<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
implements="mx.controls.listClasses.IDropInListItemRenderer">
<mx:Script>
<![CDATA[
import mx.controls.DataGrid;
import components.content.contents.datagrids.LoopMastersDataGrid;
import components.remix.PadDisplay.PadContent;
import mx.controls.listClasses.BaseListData;
[Embed(source='assets/play_20.png')]
[Bindable]
public var play20Img:Class;
public static const PLAYING:String="playing";
public static const LOADING:String="loading";
public static const IDLE:String="idle";
private var _listData:BaseListData;
private var _bpm:int;
private var _path:String;
private var _state:String="idle";
public function get listData():BaseListData
{
return _listData;
}
public function set listData(value:BaseListData):void
{
_listData=value;
var criteria:String = (_listData.owner as LoopMastersDataGrid).critera;
if(this._path==criteria)
{
// this track is playing
previewbutton.styleName="stopPreviewButtonStyle";
}else
{
// this track is not playing
previewbutton.styleName="playPreviewButtonStyle";
}
//trace("list data crit=="+criteria);
}
override public function set data(value:Object):void
{
super.data=value;
this._path=new String(PadContent.LOOP_ROOT + value.r + "/" + value.u + ".rocudo");
this._bpm=value.bp;
//trace(this._path);
}
private function sendPreviewRequest(event:Event):void
{
switch(this._state)
{
case(PreviewPlay.IDLE):
(listData.owner as LoopMastersDataGrid).dispatchEvent(new PreviewPlayEvent(PreviewPlayEvent.PLAY,this._bpm,this._path));
break;
case(PreviewPlay.LOADING):
// preview play probably shouldnt care about loading
break;
case(PreviewPlay.PLAYING):
(listData.owner as LoopMastersDataGrid).dispatchEvent(new PreviewPlayEvent(PreviewPlayEvent.STOP,this._bpm,this._path));
break;
}
//dispatchEvent(new PreviewPlayEvent(PreviewPlayEvent.PLAY,this._bpm,this._path));
}
/** override protected function commitProperties():void
{
super.commitProperties();
this._state=PreviewPlay.IDLE;
}**/
]]>
</mx:Script>
<mx:Button id="previewbutton"
width="20"
height="20" click="sendPreviewRequest(event)" styleName="playPreviewButtonStyle">
</mx:Button>
</mx:HBox>
Update
I removed my mouse down handler from the datagrid and removed the cusom component. Clicking on a item in the datagrid makes the datagrid scroll so that the item selected appears first in the list. This is the behaviour I need to stop.

TouchEvents for Flash Builder 4.5

I have successfully made my first application and imported it into my iPhone, but I can't seem to get TouchEvents to work. What am I doing wrong? Here is the code that I have currently:
package
{
import flash.display.Graphics;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.MouseEvent;
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class TestIos extends Sprite
{
private var boll:Sprite = new Sprite;
private var radius:Number = 40;
public function TestIos()
{
super();
// support autoOrients
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
this.addChild(boll);
this.drawBoll();
// Add events
boll.addEventListener(TouchEvent.TOUCH_BEGIN,onTouchBegin);
boll.addEventListener(TouchEvent.TOUCH_TAP,onTouchTap);
}
private function onTouchBegin(e:TouchEvent):void {
var g:Graphics = boll.graphics;
g.clear();
g.beginFill(0xcc66cc,1);
g.drawCircle(150,radius,radius);
boll.scaleX = boll.scaleY = 1.25;
boll.addEventListener(TouchEvent.TOUCH_END,onTouchEnds);
boll.addEventListener(TouchEvent.TOUCH_MOVE,onTouchMove);
}
private function onTouchMove(e:TouchEvent):void {
boll.x = e.stageX;
boll.y = e.stageY;
}
private function onTouchTap(e:TouchEvent):void {
var g:Graphics = boll.graphics;
g.clear();
g.beginFill(0x33cc33,1);
g.drawCircle(150,radius,radius);
boll.scaleX = boll.scaleY = 1;
}
private function onTouchEnds(e:TouchEvent):void {
this.drawBoll();
boll.removeEventListener(TouchEvent.TOUCH_MOVE,onTouchMove);
boll.removeEventListener(TouchEvent.TOUCH_END,onTouchEnds);
}
private function drawBoll():void {
var g:Graphics = boll.graphics;
g.clear();
g.beginFill(0x3399cc,1);
g.drawCircle(150,radius,radius);
boll.scaleX = boll.scaleY = 1;
}
}
}
I would recommend you look at the API and examples. In this case, it seems you're missing the Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; declaration.

save button error in AS project

Whats wrong with the following code,There is an error at
saveButton.visible = false;
discardButton.visible = false;
package
{
import flash.display.Sprite;
import flash.media.Camera;
import flash.media.Video;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.events.MouseEvent;
import flash.net.FileReference;
import flash.utils.ByteArray;
import com.adobe.images.JPGEncoder;
public class caml extends Sprite
{
private var camera:Camera = Camera.getCamera();
private var video:Video = new Video();
private var bmd:BitmapData = new BitmapData(320,240);
private var bmp:Bitmap;
private var fileReference:FileReference = new FileReference();
private var byteArray:ByteArray;
private var jpg:JPGEncoder = new JPGEncoder();
public function caml()
{
saveButton.visible = false;
discardButton.visible = false;
saveButton.addEventListener(MouseEvent.MOUSE_UP, saveImage);
discardButton.addEventListener(MouseEvent.MOUSE_UP, discard);
capture.addEventListener(MouseEvent.MOUSE_UP, captureImage);
if (camera != null)
{
video.smoothing = true;
video.attachCamera(camera);
video.x = 140;
video.y = 40;
addChild(video);
}
else
{
trace("No Camera Detected");
}
}
private function captureImage(e:MouseEvent):void
{
bmd.draw(video);
bmp = new Bitmap(bmd);
bmp.x = 140;
bmp.y = 40;
addChild(bmp);
capture.visible = false;
saveButton.visible = true;
discardButton.visible = true;
}
private function saveImage(e:MouseEvent):void
{
byteArray = jpg.encode(bmd);
fileReference.save(byteArray, "Image.jpg");
removeChild(bmp);
saveButton.visible = false;
discardButton.visible = false;
capture.visible = true;
}
private function discard(e:MouseEvent):void
{
removeChild(bmp);
saveButton.visible = false;
discardButton.visible = false;
capture.visible = true;
}
}
}
I guess this is a document root class and the buttons is added to stage in the flash fla file. In that case you need to add the buttons to your declaration as public members:
public var saveButton : Button;
public var discardButton : Button;
UPDATE
I never use the flash components myself but you might find an answer here on how to use Flash components in Flashbuilder:
http://www.moock.org/blog/archives/000253.html
http://www.ruttencutter.com/?p=20

Resources