Youtube as3 player API errors - actionscript-3

I'm trying to get the youtube as3 chromeless player to work. I have followed the youtube as3 API examples and this is what i got so far:
public class Main extends Sprite
{
Security.allowDomain("*");
private var player:Sprite;
private var loader:Loader;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
}
private function onLoaderInit(e:Event):void
{
player = Sprite(loader.content);
addChild(player);
player.addEventListener("onReady", onPlayerReady);
player.addEventListener("onError", onPlayerError);
player.addEventListener("onStateChange", onPlayerStateChange);
player.addEventListener("onPlayerQualityChange", onVideoPlaybackQualityChange);
}
private function onPlayerReady(e:Event):void
{
trace("Player ready: " + Object(e.target).Data);
// player.loadVideoById("uad17d5hR5s");
}
private function onPlayerError(e:Event):void
{
trace("Player error: " + Object(e).Data);
}
private function onPlayerStateChange(e:Event):void
{
// trace("Player state: " + Object(e).Data);
}
private function onVideoPlaybackQualityChange(e:Event):void
{
trace("Video quality: " + Object(e).Data);
}
}
The onPlayerReady and the onStateChange events fires but i get errors. When tracing Object(e).Data i get this error:ReferenceError: Error #1069: the property Data was not found for com.google.youtube.event.ExternalEvent and there is no standard value.(stranslated from swedish)
When changing to Object(e.target).Data it traces "undefined" and Object(e.target) traces "[object SwfProxy]".
If i try player.loadVideoById("uad17d5hR5s"); i get this error:
1061: Call to a possibly undefined method loadVideoById through a reference with static type flash.display:Sprite.

I don't think you should cast loader.content as a Sprite. You should cast the player to an Object type instead. The player variable is only to access the API calls. In terms of placing, moving and adding to the display list, use the Loader object that contains the SwfProxy object. Try this code:
package
{
import flash.display.*;
import flash.events.*;
import flash.system.Security;
import flash.net.*;
public class Main extends MovieClip
{
Security.allowDomain("*");
private var player:Object;
private var loader:Loader;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
}
private function onLoaderInit(e:Event):void
{
player = Sprite(loader.content);
addChild(loader);
player.addEventListener("onReady", onPlayerReady);
player.addEventListener("onError", onPlayerError);
player.addEventListener("onStateChange", onPlayerStateChange);
player.addEventListener("onPlayerQualityChange", onVideoPlaybackQualityChange);
}
private function onPlayerReady(e:Event):void
{
trace("Player ready: " + Object(e.target).Data);
player.loadVideoById("uad17d5hR5s");
player.setSize(480, 365);
}
private function onPlayerError(e:Event):void
{
trace("Player error: " + Object(e).Data);
}
private function onPlayerStateChange(e:Event):void
{
// trace("Player state: " + Object(e).Data);
}
private function onVideoPlaybackQualityChange(e:Event):void
{
trace("Video quality: " + Object(e).Data);
}
}
}

Related

Adobe AIR getQualifiedDefinitionNames

I have a problem with getQualifiedDefinitionNames, when I compile with AIR 20 I get
Main
gameBg_png$c19135a2672bad8837da970f47c7278f-30390368
and when I compile with Apach Flex 4.15.0 or Adobe Animate CC it returnes everything as expected!
Main
Main__gamebg
how to fix it with AIR, that it returned Main__gamebg class?
my sample code:
package{
import flash.display.MovieClip;
import flash.events.Event;
public class Main extends MovieClip {
[Embed(source="../assets/gameBg.png")]
public const _gamebg:Class;
public function Main() {
super();
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
var definitions:*;
if (this.loaderInfo.applicationDomain.hasOwnProperty("getQualifiedDefinitionNames")) {
definitions = this.loaderInfo.applicationDomain["getQualifiedDefinitionNames"]();
for (var i:int = 0; i < definitions.length; i++) {
trace(definitions[i])
}
}
}
}
}
http://forum.starling-framework.org/topic/getqualifieddefinitionnames-porblem?replies=5#post-90611
this trick works.
///////////////
// SomeImage.as
///////////////
[Embed(source="someimage.png")]
public class SomeImage extends Bitmap{
public function get dimensions(): String{
return width + "x" + height;}
}
/////////////
// MyClass.as
/////////////
public class MyClas{
public function foo(): void{
// Instantiate the bound class to get the embedded image
var someImage:SomeImage = new SomeImage();
// ... do whatever you'd like with someImage
trace("Dimensions: " + someImage.dimensions);
}
}

ActionScript 3.0 - Dispatch event class to class

I'm working in Action Script 3.0 and I have a question in DispatchEvent class.
following code is standalone class.
I want to dispatch event to 'main' class and 'sub' class when event occured.
I'm stuck on this issue. please help me.
package com
{
import flash.events.*;
import flash.display.MovieClip;
import com.sub;
public class main extends MovieClip
{
public static const BTN_CLICKED:String = "btn_Clicked";
public function main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
public function init(e:Event = null):void
{
var flashVars:Object = {};
removeEventListener(Event.ADDED_TO_STAGE, init);
if(parent != null && parent.parent != null)
{
flashVars = parent. parent.loaderInfo.parameters;
}
else
{
flashVars = this.root.loaderInfo.parameters;
}
//entry point
var subClass:sub = new sub;
subClass.init();
btn.addEventListener(MouseEvent.CLICK, onClick);
addEventListener(BTN_CLICKED, onbtnClicked, false, 0, true);
}
public function onClick(e:MouseEvent)
{
dispatchEvent(new Event(BTN_CLICKED));
}
public function onbtnClicked(e:Event)
{
trace("clicked");
}
}
}
and below is 'sub' class.
package com
{
import flash.events.*;
import flash.display.MovieClip;
import com.main;
public class sub extends MovieClip
{
public function sub():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
public function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
//entry point
trace("sub class loaded");
}
}
}
yes, there's nothing in 'sub' class... how can I get dispatch event in sub class?

AS3 - Referencing the Stage after Preloader Implementation

Ive just finished the basic structure of a little game and saved the simple preloader till last. Silly me.
After numerous tutorials I found this one that worked for me - Pre Loader in Flash Builder
The preloader works and the game is on the stage, but freezes instantly. Any reference to the stage in my LevelOne code throws up errors. error #1009: cannot access a property or method of a null object reference.
Before implementing the Preloader, my Application Class (RookiesGame) was used as a level switcher. Each level is contained in a Sprite. RookiesGame starts by adding LevelOne to stage, then once player completes it, RookiesGame removes LevelOne and adds LevelTwo to stage etc.
The level classes reference the stage with the _stage variable.
Since Ive been learning this structure, the preloader becoming the application class and RookiesGame becoming just another class has really confused me. Shouldn’t the _stage var still work? Is it okay to keep RookiesGame as a level switcher?
Anyway main problem is referencing the stage from the Level Classes.
Current code:
Preloader Class
Works fine, game starts.
package
{
import flash.display.DisplayObject;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.utils.getDefinitionByName;
[SWF(width="650", height="450", backgroundColor="#FFFFFF", frameRate="60")]
public class Preloader extends Sprite
{
// Private
private var _preloaderBackground:Shape
private var _preloaderPercent:Shape;
private var _checkForCacheFlag:Boolean = true;
// Constants
private static const MAIN_CLASS_NAME:String = "RookiesGame";
public function Preloader()
{
trace("Preloader: Initialized.")
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function dispose():void
{
trace("Preloader: Disposing.")
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
if (_preloaderBackground)
{
removeChild(_preloaderBackground);
_preloaderBackground = null;
}
if (_preloaderPercent)
{
removeChild(_preloaderPercent);
_preloaderPercent = null;
}
}
// Private functions
private function onAddedToStage(e:Event):void
{
trace("Preloader: Added to stage.");
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.scaleMode = StageScaleMode.SHOW_ALL;
stage.align = StageAlign.TOP_LEFT;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(e:Event):void
{
if (_checkForCacheFlag == true)
{
_checkForCacheFlag = false;
if (root.loaderInfo.bytesLoaded >= root.loaderInfo.bytesTotal)
{
trace("Preloader: No need to load, all " + root.loaderInfo.bytesTotal + " bytes are cached.");
finishedLoading();
}
else
beginLoading();
}
else
{
if (root.loaderInfo.bytesLoaded >= root.loaderInfo.bytesTotal)
{
trace("Preloader: Finished loading all " + root.loaderInfo.bytesTotal + " bytes.");
finishedLoading();
}
else
{
var percent:Number = root.loaderInfo.bytesLoaded / root.loaderInfo.bytesTotal;
updateGraphic(percent);
trace("Preloader: " + (percent * 100) + " %");
}
}
}
private function beginLoading():void
{
// Might not be called if cached.
// ------------------------------
trace("Preloader: Beginning loading.")
_preloaderBackground = new Shape()
_preloaderBackground.graphics.beginFill(0x333333)
_preloaderBackground.graphics.lineStyle(2,0x000000)
_preloaderBackground.graphics.drawRect(0,0,200,20)
_preloaderBackground.graphics.endFill()
_preloaderPercent = new Shape()
_preloaderPercent.graphics.beginFill(0xFFFFFFF)
_preloaderPercent.graphics.drawRect(0,0,200,20)
_preloaderPercent.graphics.endFill()
addChild(_preloaderBackground)
addChild(_preloaderPercent)
_preloaderBackground.x = _preloaderBackground.y = 10
_preloaderPercent.x = _preloaderPercent.y = 10
_preloaderPercent.scaleX = 0
}
private function updateGraphic(percent:Number):void
{
// Might not be called if cached.
// ------------------------------
_preloaderPercent.scaleX = percent
}
private function finishedLoading():void
{
var RookiesGame:Class = getDefinitionByName(MAIN_CLASS_NAME) as Class;
if (RookiesGame == null)
throw new Error("Preloader: There is no class \"" + MAIN_CLASS_NAME + "\".");
var main:DisplayObject = new RookiesGame() as DisplayObject;
if (main == null)
throw new Error("Preloader: The class \"" + MAIN_CLASS_NAME + "\" is not a Sprite or MovieClip.");
addChild(main);
dispose();
}
}
}
RookiesGame Class (used to be application class)
Any references to the stage threw up #1009 error, which stopped when I changed stage.addChild to this.addChild
Ive not got to the level switch handler yet with the preloader, so I dont know how stage.focus will work either!
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
public class RookiesGame extends Sprite
{
private var _levelOne:LevelOne;
private var _levelTwo:LevelTwo;
public function RookiesGame()
{
_levelOne = new LevelOne(stage);
_levelTwo = new LevelTwo(stage);
this.addChild(_levelOne);
this.addEventListener("levelOneComplete",levelTwoSwitchHandler);
}
private function levelTwoSwitchHandler(event:Event):void
{
this.removeChild(_levelOne);
_levelOne = null;
this.addChild(_levelTwo);
stage.focus = stage;
}
}
}
LevelOne Class
Lots of #1009 errors. Anything referencing the stage.
Class is huge so I'll highlight problem chunks.
The #1009 error when referencing stage, adding the keyboard listeners.
_stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
Also #1009 when referencing stage to check stage Boundaries. Cant just change stage. to this. anymore.
private function checkStageBoundaries(gameObject:MovieClip):void
{
if (gameObject.x < 50)
{
gameObject.x = 50;
}
if (gameObject.y < 50)
{
gameObject.y = 50;
}
if (gameObject.x + gameObject.width > _stage.stageWidth - 50)
{
gameObject.x = _stage.stageWidth - gameObject.width - 50;
}
if (gameObject.y + gameObject.height > _stage.stageHeight - 50)
{
gameObject.y = _stage.stageHeight - gameObject.height - 50;
}
}
I reference _stage later in the program to remove the event listeners. Thats it.
_stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
How can I reference the stage, without these errors and keep RookiesGame as the level switcher.
LevelOne Class Structure
To show how I use(d) _stage.
package
{
//import classes
public class LevelOne extends Sprite
{
//Declare the variables to hold the game objects
//A variable to store the reference to the stage from the application class
private var _stage:Object;
public function LevelOne(stage:Object)
{
_stage = stage;
this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function addedToStageHandler(event:Event):void
{
startGame();
this.removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function startGame():void
{
//Includes _stage references that mess everything up.
}
private function levelCleared():void
{
//When Level finished, dispatch event to tell RookiesGame to switch levels.
dispatchEvent(new Event("levelOneComplete", true));
}
}
}
Sorry if thats confusing, but if you can help me reference the stage via LevelOne and RookiesGame classes, It would be much appreciated.
You are passing in a null stage to LevelOne from your RookiesGame class. Whenever you instantiate a RookiesGame the constructor will run first, it has not been added to the display list yet so its inherited reference to stage is null. What you need to do is add an event listener for ADDED_TO_STAGE in the RookiesGame class:
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
public class RookiesGame extends Sprite
{
private var _levelOne:LevelOne;
private var _levelTwo:LevelTwo;
public function RookiesGame()
{
addEventListener( Event.ADDED_TO_STAGE, onAdded );
}
//added to stage event
private function onAdded( e:Event ):void {
removeEventListener( Event.ADDED_TO_STAGE, onAdded );
_levelOne = new LevelOne(stage);
_levelTwo = new LevelTwo(stage);
this.addChild(_levelOne);
this.addEventListener("levelOneComplete",levelTwoSwitchHandler);
}
...
}
Also if you are using addChild() call for LevelOne as in addChild(_levelOne) it has its own reference to stage after it's been added to the display list, you do not need to create a _stage variable for those classes if you are adding them to the display list.
Also you have the listener for ADDED_TO_STAGE in LevelOne, where the stage variable would have no longer been null, so you can remove your class variable _stage entirely.

loaderInfo.addEvenListener doesn't work

I made a code for preloader that worked when it was written in frame actions. But then I decided to move all the code to classes and a bit reworked it. And now it doesn't work. Function that listener should call is just not called, and I started getting errors when address to argument event in this not-called function.
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.ProgressEvent;
public class Preloader extends MovieClip {
public function Preloader() {
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event):void {
trace("init started");
removeEventListener(Event.ADDED_TO_STAGE, init);
loaderInfo.addEventListener(ProgressEvent.PROGRESS, showProgress);
trace("init completed");
}
private function showProgress(e:Event):void {
trace(loaderInfo.bytesLoaded);
/*info_txt.text = Math.floor(e.bytesLoaded/e.bytesTotal*100) + "%"
if (e.bytesLoaded==e.bytesTotal) {
loaderInfo.removeEventListener(ProgressEvent.PROGRESS, showProgress);
finalizeLoading();
}
/**/
}
private function finalizeLoading():void {
removeChild(info_txt);
var startGame_btn = new StartGame_btn();
addChild(startGame_btn);startGame_btn.x=395;startGame_btn.y=290;
}
}
}
When I uncomment /*info_txt... part. I get this:
Access of possibly undefined property bytesLoaded through a reference with static type flash.events:Event.
Access of possibly undefined property bytesTotal through a reference with static type flash.events:Event.
Access of possibly undefined property bytesLoaded through a reference with static type flash.events:Event.
Access of possibly undefined property bytesTotal through a reference with static type flash.events:Event.
Change loaderInfo to root.loaderInfo in the init method for listening root loaderInfo object. When your script were in timeline this object were documentClass and root simultaneously, so your code have worked properly.
What about errors, just change type of e argument from Event to ProgressEvent in the showProgress method, because Event doesn't gave such properties.
There is a lot wrong with your code.
Here is a simple loader with some of your code added. at the worst it should point you in the right direction.
package {
import flash.display.MovieClip;
import flash.errors.IOError;
import flash.events.AsyncErrorEvent;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
public class myPreloader extends MovieClip {
public var context:LoaderContext = new LoaderContext();
public var myLoader:Loader = new Loader();
public var url:URLRequest;
public function myPreloader() {
context = new LoaderContext();
context.checkPolicyFile = true;
myLoader = new Loader();
myLoader.addEventListener(AsyncErrorEvent.ASYNC_ERROR, errorHandlerAsyncErrorEvent);
myLoader.addEventListener(IOErrorEvent.IO_ERROR, errorHandlerIOErrorEvent);
myLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandlerSecurityErrorEvent);
myLoader.contentLoaderInfo.addEventListener(Event.INIT, initHandler);
myLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, infoIOErrorEvent);
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressListener);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
url = new URLRequest("test.swf"); // change this to whatever it is you are loading
myLoader.load( url,context );
myLoader.load( url);
}
public function progressListener (e:ProgressEvent):void{
trace("Downloaded " + e.bytesLoaded + " out of " + e.bytesTotal + " bytes");
info_txt.text = info_txt.text = Math.floor(e.bytesLoaded/e.bytesTotal*100) + "%"
}
public function onLoadComplete( e:Event ):void{
trace( 'onLoadComplete' );
removeChild(info_txt);
var startGame_btn = new StartGame_btn();
addChild(startGame_btn);
startGame_btn.x = 395;
startGame_btn.y=290;
}
public function initHandler( e:Event ):void{
trace( 'load init' );
}
public function errorHandlerErrorEvent( e:ErrorEvent ):void{
trace( 'errorHandlerErrorEvent ' + e.toString() );
}
public function infoIOErrorEvent( e:IOErrorEvent ):void{
trace( 'infoIOErrorEvent ' + e.toString() );
}
public function errorHandlerIOErrorEvent( e:IOErrorEvent ):void{
trace( 'errorHandlerIOErrorEvent ' + e.toString() );
}
public function errorHandlerAsyncErrorEvent( e:AsyncErrorEvent ) :void{
trace( 'errorHandlerAsyncErrorEvent ' + e.toString() );
}
public function errorHandlerSecurityErrorEvent( e:SecurityErrorEvent ):void{
trace( 'errorHandlerSecurityErrorEvent ' + e.toString() );
}
}
}

AS3 Keyboard events

How would one go about adding event listeners for multiple keystrokes, for example if the up and right buttons are pressed player goes diagonally in that direction.
Check out the following code, I store the pressed key in a object and then animated a sprite using the object :
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Main extends Sprite
{
private var _keys:Object = { };
private var _sprite:Sprite = new Sprite;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
_sprite.graphics.beginFill(0xff0000, 1);
_sprite.graphics.drawRect(0, 0, 40, 40);
_sprite.graphics.endFill();
_sprite.x = 100;
_sprite.y = 100;
addChild(_sprite);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onKeyDown(e:KeyboardEvent):void
{
_keys[e.keyCode] = true;
}
private function onKeyUp(e:KeyboardEvent):void
{
_keys[e.keyCode] = false;
}
private function onEnterFrame(e:Event):void
{
if (_keys[Keyboard.UP])
{
_sprite.y --;
}
if (_keys[Keyboard.DOWN])
{
_sprite.y ++;
}
if (_keys[Keyboard.RIGHT])
{
_sprite.x++;
}
if (_keys[Keyboard.LEFT])
{
_sprite.x--;
}
}
}
}