The new YouTube AS3 Chromeless API in Flex, Air, Flash
I was very pleased that YouTube released a ActionScript 3 API for their Chromeless Player. I looked at some availabe code snippets on different blogs and unfortunateley, I had to realize that the API is not really object-oriented and a little bit annoying to work with (because of the missing code completion).
My current project - an independent Web Video Player - is still using the old workaround YouTube API Tubeloc and I have to change this. That is the reason why I created a Flex Component for the new YouTube AS3 API. If you would like to use my code for your Flex or Air projects, please feel free to use it and if you will find some bugs, please leave a comment!
Now I will start with some explanations of my code. I create 4 classes, which manage the whole YouTube Chromeless API. The class YouTubeAs3 contains all the most important functions and is based on the Flex Framework(!). The classes AirYouTube and FlexYouTube extends the YouTubeAs3 class. Both classes are Flex Framework based classes. I had to divide the YouTubeAs3 class into these 2 classes, because the Adobe Air environment don't support the command Security.allowDomain() and it is cleaner to use this command for a web-based projects. So therefore please use the FlexYouTube component for web-based projects and the AirYouTube component for your Air projects. The fourth class FlashYouTube is an only Flash plattform based class, that should be very handy to use for non-Flex projects.
The other classes just simplify the coder's life. So I created some static classes for the various video quality parameters (YouTubeVideoQuality Class), the various PlayerStates (YouTubePlayingState), the YouTube errors (YouTubeError) and of course the available YouTube events (YouTubeEvent).
I wrote an example application for you, which should be very easy to understand. In this very small Flex application you can stop, play and pause the YouTube videos:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
//---------------------------------- // YouTube Player Control //---------------------------------- private function handlePlay(event:MouseEvent):void { youTubePlayer.playVideo(); this.addEventListener(Event.ENTER_FRAME,handlePlayingTime); } private function handlePause(event:MouseEvent):void { youTubePlayer.pauseVideo(); this.removeEventListener(Event.ENTER_FRAME,handlePlayingTime); } private function handleStop(event:MouseEvent):void { youTubePlayer.stopVideo(); this.removeEventListener(Event.ENTER_FRAME,handlePlayingTime); } // frame-based Intervall for showing loading and playing process private function handlePlayingTime(e:Event):void { labelTime.text = youTubePlayer.getCurrentTime() + " / " + youTubePlayer.getDuration(); progresPlayingVideo.minimum = 0; progresPlayingVideo.maximum = youTubePlayer.getDuration(); progresPlayingVideo.setProgress(youTubePlayer.getCurrentTime(),youTubePlayer.getDuration()); progressLoadVideo.minimum = 0; progressLoadVideo.maximum = youTubePlayer.getVideoBytesTotal(); progressLoadVideo.setProgress(youTubePlayer.getVideoBytesLoaded(), youTubePlayer.getVideoBytesTotal()); } |
Some behaviours of this Flex-based YouTube component is adjusted for the Flex Framework. If you would like to change the size of the YouTube Player, you can use the witdh and height properties of the component. Furthermore there exists some other properties:
1 2 3 |
[Bindable] public var volume:int; // Value between 0 and 100 [Bindable] public var playerState:Number; // Read-only!!!! [Bindable] public var playbackQuality:String; // Use the static variables of the YouTubeVideoQuality class |
Handling and managing of the YouTubeEvents are the last thing I would like to explain. I support the same 4 events, which the YouTube API supports. The only difference is that I wrapped the data of the events in a special YouTube Event for an simpler event handling and code completion.
1 2 3 4 |
[Event(name="youtubeStatus", type="de.derhess.video.youtube.YouTubeEvent")] [Event(name="youtubePlayerLoaded", type="de.derhess.video.youtube.YouTubeEvent")] [Event(name="youtubeError", type="de.derhess.video.youtube.YouTubeEvent")] [Event(name="youtubeVideoQuality", type="de.derhess.video.youtube.YouTubeEvent")] |
So here I is my code of my app. I think it is very self-explanatory...
1 2 3 4 |
/* Here should be some code but wordpress always crashed because of parsing problems... Please download the code and look at line number 23-112 in the src folder the file flex_youTube.mxml */ |
The rest of the functions contains exactly the same functionality as the YouTube API. If something ambiguous, please look at the YouTube API documentation or leave a comment. THX!
Download the Flex YouTube components and source code
hey man, thanks for the classes,
one question though: is there a way to destroy the player??
Thanks so much for this! I went about creating an interface for the youtube api as soon as it came out, but I see you beaten me too it (and added so much more as well!).
Many thanks again, have you thought of submitting this to google? I think they need help with this kind of thing.
@munnaz1
yes, you can destroy the player. Look at the example app. There is a button with the label “destroy”. Click this button and the player instance should be destroyed…
@enzuguri
Hey, I have not beaten you. We are one community! 🙂 so now you can spend your time for other important things 😉 Yeah, it is a little bit sad, that google have not done by themself… the same is valid for the vimeo api team… I think they are not very interested in the independent or small Flash / Flex developer life. Anyway, I am happy that they provide such a kind of APIs for us.
Ah,.. genau was ich gesucht habe. Darf ich deinen Code für ein opensource projekt benutzen?
Hi FJ,
du kannst meinen Code gerne für dein Open Source Projekt benutzen. Wäre cool wenn du irgendwo n kleinen Verweis machen könntest, dass du meine Klassen benutzt hast. So quasi die eine Hand wäscht die andere 😉
Grüße aus Linz
Flo
thanks. Natürlich. Werde dir bescheid geben sobald ich soweit bin.
http://github.com/FlashJunior/OSFlashVideoPlayer
wer mithelfen will ist herzlich willkommen 🙂
I resized the application and tried to put youtube:FlexYouTube inside a canvas to position it, but it is always half off the screen and to the upper right. How do I position it?
Hi Sam,
I tried to reproduce your bug, but I had no success. Could you please post your code? I tried almost everything with the FlexYouTube Component inside a Canvas and it works fine for me… Thx
Hi,
i have try your project in a new air application and it is working fine.
But i want to intergrate this player in a bigger application, so i have added the player to my components, changing the “application” tag in a spark “group”.
I have a sanddbox violation when running it : [SWF] /apiplayer – 3 724 octets après la décompression
Warning: Domain s.ytimg.com does not specify a meta-policy. Applying default meta-policy ‘master-only’. This configuration is deprecated. See http://www.adobe.com/go/strict_policy_files to fix this problem.
[SWF] /yt/swf/apiplayer3-vfl155676.swf – 171 820 octets après la décompression
[SWF] /[[IMPORT]]/s.ytimg.com/yt/swf/apiplayer3-vfl155676.swf – 1 927 octets après la décompression
*** Security Sandbox Violation ***
SecurityDomain ‘http://www.youtube.com/apiplayer?version=3’ tried to access incompatible context ‘app:/Potati.swf’
After the error warning, it is working fine…
If i try to add in the mxml file of your player :
Security.allowInsecureDomain(“*”);
Security.allowDomain(“*”);
, i have a security error :
SecurityError: Error #3207: Application-sandbox content cannot access this feature.
at flash.system::Security$/allowInsecureDomain()
I do not know how to put the player in another sandbox of my air app…
Do you have an idea on how to solve this issue ?
Thx
I was wondering if you could point me the direction of learning how to implement your code in Flash?
I am a total Newbie and just started to use Flash. I created an Indesign document and exported it to Flash and now want to add YouTube Movies. But I can’t figure it out. I thought I would load a component but I am totally lost.
If you can give me some clues I would appreciate your assistance.
Robert
Hi Robert,
I don’t know how InDesign deals with Flash Content. But in Flash you can write:
import de.derhess.video.youtube.*;
function handlePlayerLoaded(event:YouTubeEvent):void
{
// Play the VideoID you want
youTubePlayer.cueVideoById(“jAHYJX4-glU”,0,YouTubeVideoQuality.DEFAULT);
}
var youTubePlayer:FlashYouTube = new FlashYouTube();
// Add and check if the YouTube Player API is loaded
youTubePlayer.addEventListener(YouTubeEvent.PLAYER_LOADED,handlePlayerLoaded);
//Add your YouTube Player to the rendering List
addChild(youTubePlayer);
I hope this code snippet helps.
Hi, thank you very much for the code!
I am currently using it in a project and seem to have a memory leak. My FlashYouTube instance is not freed from memory although I call destroy() and set it to null. (I also removed the INIT handler from the loader). Of course I also remove all listeners from the instance etc. But it still stays in memory.
Do you know of such an issue?
Thanks a lot!
@Marc-André Weibezahn
Hi, thanks for your feedback! Hm, I don’t know this problem, but you can try to remove the loader instance from the DisplayList. If you look at the handleLoaderInit code, you can see that I added the loader instance, but I never removed it in the destroy function… Don’t know why I have not done it… Maybe it solves your problem… Otherwise please check the YouTube API again. Since I published these classes the YouTube API got some updates.
Thank you for this suggestion. I am removing the loader already, no success. I will check the API 🙂
Update: I couldn’t check if it works for my problem yet, but it seems like a good idea to use unloadAndStop() instead of unload() for the loader object when destroying. 🙂
Hey, thank you very much for your advice! Much appreciated 🙂 I will update the classes soon…
Hi, I tested it, and with unloadAndStop() the FlashYouTube class is released from memory. What is not released (and what we probably can’t do a thing about) is a ton of classes from youtube’s player object, see here: http://weibezahn.com/youtube_classes.png
I wonder if I should file a bug over there at the API site – but I am not sure if YouTube or Adobe is to blame for this 😉
HI Dude…..
I need some help and i’m desperate.
I tried to make it works on my machine but i encoutered a issue…
I cant load some videos cos i receive this error : Embedding not allowed
ID video is : qrO4YZeyl0I
I cant understand how come this video works on your small flex application but i cant make
it works on my machine…
Can you help me please????? :'(
Nobody could help me 🙁 ??
I don’t know what exactly your problem is. It seems that this video is not allowed in your country. Maybe my example is working because my server is in Germany… It is important where the API Client request comes from. But I am not sure if this is really your problem…
Hi,
First, thx for your work and sharing !
I’m having exactly the same problem as Christophe in AIR, when i try to use AiryouTube on cueVideoById got this in the debug :
[SWF] /apiplayer – 3 374 octets après la décompression
[SWF] /yt/swfbin/apiplayer3-vfl4hk1e1.swf – 228 328 octets après la décompression
*** Security Sandbox Violation ***
SecurityDomain ‘http://s.ytimg.com/yt/swfbin/apiplayer3-vfl4hk1e1.swf’ tried to access incompatible context ‘app:/Main.swf’
don’t know what to do … any ideas ?
Hi,
Thanks a lot for this great piece of code. Can I use this in one of my project? Also I need help to integrate full-screen mode in my project. I however able to turn it to full-screen but I need the video only to show in the full-screen mode. Could you help?
Hi Shantanu,
yes you can use the code for your project. I used the MIT license. You can switch your application to FullScreen Mode (here a Full Screen tutorial) and resize the youtube player size… That’s all…
Best regards,
Florian
Hello Florian,
Thanks a ton for your fast response. Any idea about playing yahoo videos in Flash Player? Is there any API as such for AS 3.0?
Regards,
Shan
I don’t know any public API for the Yahoo Videos. I only found these two APIs related to video content…
http://mediaplayer.yahoo.com/
http://developer.yahoo.com/connectedtv/
Great example. Thank you! It helped us overcome a YouTube Security Sandbox Error (http://s.ytimg.com/) we were getting.
Hi Florian
Your code will be of great help for me, but I have a question?
Is it possible to create a button which will make possible a change between 2 videos but will continue the playback time from the same place where the first video left…
to make it a simpler, we start playing a video and at time 1.24 we press the button and the other video starts continuing at the same time (frame)…
by my logic there is an analogy with the playback quality button, but here we change the entire video not just its quality (in fact i guess the change in quality means move to the same (another) video with higher quality)
if you can help me in this point it would be great
all the best
thanks in advance 🙂
@Agon
Hi Agon, that should be possible. Store the currentTime with youTubeVideo1.getCurrentTime() then call the function youTubeVideo2.loadVideoById(“yourNewVideoID”,youTubeVideo1.getCurrentTime());
That should work… If not… try to play the new Video and jump to the time…
youTubeVideo2.loadVideoById(“yourNewVideoID”);
youTubeVideo2.playVideo();
youTubeVideo2.seekTo(youTubeVideo1.getCurrentTime());
that should work, too. But I don’t believe that frame accuracy is possible. You can jump to the exact second but the keyframes of encoding might differ. The seek function can only jump to the encoded keyframe (I-Frame). For more tech info please check: http://en.wikipedia.org/wiki/Video_compression_picture_types
I’ve not tried it yet but I will as soon as possible, since I’ve been busy with another project, what I am amazed about is, your response time, I thought my question will be the same as the other questions posted in other “big-brain” fellas blogs who usually don’t care about helping around…
Again, thank you very much, I don’t know when I’ll be able to implement the code but I’ll try to hit you back again…
Stay in peace
All the best
Hi Florian,
I’m back again, this time I’d like to know what changes should be done to the code so we manage to load videos from local disk and not from the youtube?
Thanks in advance,
All the best 🙂
@Agon
Hi
for this please check Lee Brimelow’s great Tutorial Site:
http://gotoandlearn.com Check the video player tutorials and especially this one http://gotoandlearn.com/play.php?id=46
For coding, the classes NetConnection, Netstream, Video are important for you. Here is a nice open source video player
http://code.google.com/p/apdev-videoplayer/
http://apdevblog.com/new-version-of-our-as3-open-source-videoplayer/
Hi Florian,
I have problems running the AirYouTube in an AIR application. The strange thing is when I use your code in an new AIR project I have:
*** Security Sandbox Violation ***
SecurityDomain ‘http://www.youtube.com/apiplayer?version=3‘ tried to access incompatible context but the you tube video loads and plays ok. When I try to include your code in a bigger AIR project I get the same security error but the video isn’t showing at all. I know that the security model for AIR is different and I can’t use Security.allowDomain. The only solution I have found so far is with HTMLLoader but it isn’t working for me because I need events like video over(playerStateChanged).
Any ideas will be appreciated.
@Vasil Pavlov
I have figured it out, it was my fault. It’s working with a Security Sandbox Violation warning. But from what I have found there is no way to get rid of it in AIR application. The application is for internal company use only so it’s suits me.
@Vasil Pavlov
Hi Vasil,
I recognized this Securtiy Sandbox Warning, too. Unfortunately, I have not tried anything for solving it… and I have no real idea, what can be done for solving it. Maybe the youTube Forum has a solution?! Sorry
@Vasil Pavlov
Hi Vasil, how did you manage to make it work finally ? i have the same problem. Thanks!
Hi! I was trying to apply your code from within a flex mobile application, and the component did not load properly, all I’ve sen was just a blank white flash window… seems like it only works on windows/browsers but not on mobile.
did you test this code in a flex mobile application? do you have other suggestions for playing youtube videos from ‘AIR for Android’ applications? thank’s
Hi! I tried to run your code from inside a flex mobile application, and the UIComponent did not load properly, all I saw was just an empty white flash application window… it worked fine on a browser though.
did you test this code in a flex mobile application? do you have other suggestions for playing youtube videos from ‘AIR for Android’ applications? thank’s
Hi @Amir Guterman
I have not tried my classes with the Flex Mobile yet. When I created these classes, the Flex Mobile Framework was not in production…
… Polygeek postet some weeks ago a solution for Android Apps. Maybe it will help you?!
http://polygeek.com/4299_air-mobile_playing-youtube-videos-in-your-air-mobile-apps
hallo
i have problem with “Embedding not allowed: 150” when i run this code on my pc and online (in this site) it dont give a error.
LMFAO – Sorry For Party Rocking
cueVideoById: SkTt9k4Y-a8
http://www.youtube.com/watch?v=SkTt9k4Y-a8
how can i make it play on a local machine???
thx
Hi!
Well, I have a problem using FlashYouTube class in Flash CS5.5.
My code looks something like this:
var player:FlashYouTube = new FlashYouTube();
addChild(player);
player.loadVideoById(“miCDhTeeSek”, 0, ‘default’);
player.setSize(320, 480);
When testing on computer with AIR for iOS, it shows black box with nothing inside it.
But when I’m testing this on real device, it doesn’t show anything at all.
What could be the problem?
Unfortunately, I have no experiences with the YouTube API on a mobile device… I can’t help you, sorry. I just know this workaround by polygeek: http://polygeek.com/4299_air-mobile_playing-youtube-videos-in-your-air-mobile-apps
You rock. You saved my day, with this a complete solution, both for web and AIR! Thank you so much.
@Santanu.K
Hi Santanu
Could you tell how you solve the youtube player issue in Air
Hi Monica,
since this last comment some APIs have changed. Maybe the YouTube Standalone Code Example might help you:
https://developers.google.com/youtube/flash_api_reference#Standalone_sample
http://code.google.com/p/gdata-samples/source/browse/trunk/ytplayer/actionscript3/com/google/youtube/examples/AS3Player.as
The Adobe Air Documentation kinda says that the Security Class works now in Adobe Air. I am not 100% sure if I understood correctly:
http://help.adobe.com/en_US/AIR/1.5/devappsflex/WS5b3ccc516d4fbf351e63e3d118666ade46-7e5a.html
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/Security.html