Flex YouTube API and Player Samples

January 25, 2010By 28 Comments

Over the weekend I worked on some samples for Tour de Flex to show how you can interface with the YouTube APIs using Flex and ActionScript. I created four samples showing different ways to do this that you can see in tabs across the top of the YouTube sample in Tour de Flex. The details for these samples are listed below:

  1. Simple Service – this is a basic sample that shows how you can use to query the YouTube API available on Google Code. The results are returned in JSON format and deserialized using the as3corelib.swc available here. The as3corelib.swc is also included in the downloaded code from Tour de Flex. Feel free to play around with changing the HTTPService URL to another type of query with other parameters based on what is listed in the Google Code API reference to get back various types of data including user profile data, categories of videos, comments etc.

    Note: The next 3 samples used an ActionScript API to wrap the YouTube requests/responses and make them easier to work with. That API was written by Martin Legris and includes iterators for all of the different objects that might be returned (categories, authors, comments, links, etc…). I recommend checking out his blog as well, there’s a lot of useful information and resources there.

  2. Video Comments – this sample shows how you can interface with YouTube and get the comments for a selected video. Simply click an item in the grid and hit Show Comments to view the comments for that particular video. Double clicking the video will bring it up in the YouTube website.
  3. Search Favorites – this sample allows you to search the favorites of a given userid. Once the favorites are shown, you can then also view the comments for that particular video in the same way as above. Note: certain userid’s may have privacy settings that will block the call and not return any results.
  4. Embed Player – this sample shows how you can not only search YouTube, but also embed their video player in you code and interact with it to do things like set the quality of the video, cue a video, play, pause, stop etc. Once you search for a video, click it to see the player show within the sample. For more information about this player API, go here.

These samples are now available in Tour de Flex under the Cloud APIs folder so definitely check them out! It was quite fun to play around with these :). If you have any questions or issues let me know and I’ll see what I can do to help!

Filed in: Adobe FlexFlex/AIRTour de Flex Tags:

About the Author ()

Comments (28)

Trackback URL | Comments RSS Feed

Sites That Link to this Post

  1. Have you looked at Tour de Flex lately? « Greg Wilson's Ramblings | January 25, 2010
  1. Tahir Alvi says:

    Hi,

    I see the example on tourdeflex, but i think this is very simple, actuallu i need to know who many task e perform by using API.
    Thanks

  2. Adam says:

    Hi,

    I really liked your examples of using the youtube api in the TourDeFlex app. Included in the TourDeFlex app is a sample that can search youtube videos and play them once the user clicks the play button. Every video loads and plays perfectly fine in the TourDeFlex app but when I compiled the exact same code in my own flex builder project some of the video’s that could play in the TourDeFlex app wont play on mine?

    This is a bit of a strange one for me and i’m thinking maybe it’s something to do with the developer key perhaps, or is it simply copyright restrictions?

    Any help would be really great!

    Thanks
    Adam

  3. Mani says:

    Nice. Thanks for this. Gonna use it in an upcoming App soon.

  4. Ashwin says:

    I am unable to check the sample code in Tour de flex. The error encountered is:
    ======================================
    Not Found

    The requested URL /holly/YouTubeSample/YouTubeSimpleService.html was not found on this server.

    Apache/2.2.14 (Ubuntu) Server at tourdeflex.adobe.com Port 80

    ======================================

    I can access all other samples… just unable to access Youtube Api samples.
    I also reported this at http://forums.adobe.com/thread/850517?tstart=0

    Please if possible can you attach the code here.

    • devgirl says:

      Thank you, I’m looking into this!

      For now, here’s a simple sample to query the YouTube Rest API but let me know specifically what you’re looking for…

      <?xml version="1.0" encoding="utf-8"?>
      <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
      			   xmlns:s="library://ns.adobe.com/flex/spark" 
      			   xmlns:mx="library://ns.adobe.com/flex/mx">
      	<fx:Script>
      		<![CDATA[
      			import mx.events.FlexEvent;
      			import mx.rpc.events.FaultEvent;
      			import mx.rpc.events.ResultEvent;
      			
      			protected function txt_enterHandler():void
      			{
      				trace("Sending ");
      				var parms:Object = new Object();
      				parms["q"] = txt.text;
      				parms["key"] = "AI39si5_aRddWPqyMM6pJWR_mOhctEUfXAnKEQ6Kdu1AB0FbZXIhdX5y2cC0tUKJWowesi9WcP1onX2JiwcXZAQ4aNIp7Ml5wQ"; 
      				service.send(parms);
      			}
      			
      			protected function onResult(event:ResultEvent):void
      			{
      				ac = event.result.feed.entry as ArrayCollection;
      				trace("Number of results " + ac.length);
      			}
      			
      			protected function onFault(event:FaultEvent):void
      			{
      				trace("Fault " + event.fault.faultString);
      			}
      			
      		]]>
      	</fx:Script>
      	<fx:Declarations>
      		<s:ArrayCollection id="ac"/>
      		<s:HTTPService id="service"
      					   url="http://gdata.youtube.com/feeds/api/videos"
      					   fault="onFault(event)"
      					   result="onResult(event)"
      					   resultFormat="object"
      					   showBusyCursor="true"/>
      		
      	</fx:Declarations>
      	<s:layout>
      		<s:VerticalLayout paddingTop="5" paddingBottom="5" paddingLeft="5" paddingRight="5" gap="5" 
      						  horizontalAlign="left" verticalAlign="middle"/>
      	</s:layout>
      	
      	<s:HGroup horizontalAlign="center" width="100%" verticalAlign="middle">
      		<s:Label text="Enter search term:"/>
      		<s:TextInput id="txt" enter="txt_enterHandler()"/>
      		<s:Button label="Send" click="txt_enterHandler()"/>
      	</s:HGroup>
      	
      	<s:DataGrid id="dg" dataProvider="{ac}" visible="{ac.length>0?true:false}"/>
      </s:Application>
      
      

      Thanks!
      Holly

      • devgirl says:

        Here’s the sample using the API (make sure to download the youtube API swc: http://code.google.com/p/as3-youtube-data-api/):

        <?xml version="1.0" encoding="utf-8"?>
        <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="init()" viewSourceURL="srcview/index.html">
        	<mx:Script>
        		<![CDATA[
        		
        			import com.adobe.webapis.youtube.*;
        			import com.adobe.webapis.youtube.events.*;
        			import com.adobe.webapis.youtube.methodgroups.*;
        			import com.adobe.webapis.events.*;
        			import com.adobe.webapis.*; 
        			
        			[Bindable]		
        			private var service:YouTubeService;
        			
        			private function init():void
        			{
        				service = new YouTubeService("AI39si5_aRddWPqyMM6pJWR_mOhctEUfXAnKEQ6Kdu1AB0FbZXIhdX5y2cC0tUKJWowesi9WcP1onX2JiwcXZAQ4aNIp7Ml5wQ");
        			}
        			private function onUsersGetProfile( event:YouTubeServiceEvent ):void
        			{
        				trace("Get user profile " + event.data);
        				if (event.data!=null)
        					trace("Event data " + event.data);
        			}
        			private function getFavorites():void
        			{
        				service.addEventListener(YouTubeServiceEvent.USERS_GET_PROFILE, onUsersGetProfile);
        				service.users.getProfile(userid.text);	
        				service.addEventListener( YouTubeServiceEvent.USERS_LIST_FAVORITE_VIDEOS, onUsersListFavoriteVideos);
        				service.users.listFavoriteVideos(userid.text);
        			}
        			private function onUsersListFavoriteVideos(event:YouTubeServiceEvent):void
        			{
        				trace("Event data : " + event.data);
        				trace("Event error " + event.error);
        				
        			}	
        			public function getVideosListByTag():void
        			{
        				service.addEventListener(YouTubeServiceEvent.VIDEOS_LIST_BY_TAG, onVideosListByTag);
        				service.videos.listByTag(searchStr.text);
        			}
        			private function onVideosListByTag(event:YouTubeServiceEvent):void
        			{
        				trace("Event data : " + event.data);
        				trace("Event error " + event.error);
        				
        				
        			}	
        			
        		]]>
        	</mx:Script>
        	<mx:HBox>
        		<mx:Form defaultButton="{btnFaves}">
        		<mx:FormItem>
        			<mx:HBox>
        				<mx:Text text="Userid:"/>
        				<mx:TextInput id="userid"/>
        				<mx:Button id="btnFaves" label="Get Favorites" click="getFavorites()"/>
        			</mx:HBox>
        		</mx:FormItem>		
        		</mx:Form>
        		<mx:Form defaultButton="{btnSearch}">
        		<mx:FormItem>
        		</mx:FormItem>		
        		<mx:FormItem>
        			<mx:HBox>
        				<mx:Text id="search" text="Search"/>
        				<mx:TextInput id="searchStr"/>
        				<mx:Button id="btnSearch" label="Search" click="getVideosListByTag()"/>
        			</mx:HBox>
        		</mx:FormItem>		
        	</mx:Form>
        
        	</mx:HBox>
        </mx:Application>
        

        Hope this helps!
        Holly

  5. Ashwin says:

    Hi Holly,

    Thanks for your reply.

    I am looking for a sample code that will help me load videos from youtube in a list and then I can play any of those videos with a click… just the basics.

    I did try it using another example found online and encountered an error:

    Error #2044: Unhandled ioError:. text=Error #2032: Stream Error.

    So I thought I could use the code provided in TourDeFlex.. but that does not load.

    Now I tried using the second code sample you provided above and that gives the same error:

    Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: http://www.youtube.com/api2_rest?dev_id=AI39si5_aRddWPqyMM6pJWR_mOhctEUfXAnKEQ6Kdu1AB0FbZXIhdX5y2cC0tUKJWowesi9WcP1onX2JiwcXZAQ4aNIp7Ml5wQ&method=youtube.videos.list_by_tag&tag=htc&amp;

    I guess this is a very simple error but I am not able to resolve…I searched online and found that the error is encountered in many situations like..the url or file being accessed is blocked, the url might be incorrect, trying to access a file across a restricted domain..still no clue whats wrong here..

    Is the url above correct?

    Thanks for your time..

    –Ashwin

  6. Lior says:

    The code have errors and it’s still doesn’t shows up in tour de flex…
    Any chance you can provide the code again?

  7. Lior says:

    Hi Holly,
    Thanks for the quick responce!

    I’m using Flash Builder 4.5

    I’m getting an error in the 2nd line of code saying:
    “The value of attribute “xmlns:fx” associated with an element type “s:Application” must not contain the ‘<' character."

  8. Hi Lior, looks like something might have messed up the code upon paste. That Application tag *should* look like:

    s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009″
    xmlns:s=”library://ns.adobe.com/flex/spark”
    xmlns:mx=”library://ns.adobe.com/flex/mx”

    surrounded by the XML tags of course, I just can’t get them to paste in here without generating some extra junk.

    That should fix that error, thanks!
    Holly

  9. Lior says:

    Thanks again Holly!

    I fixed the App tag & the HTTPService url attribute as well.

    Now it’s working but I’m only getting the Content field (the Author, Category and comments don’t show up — returning as an [Object])

    Regarding the API, I downloaded the 0.96v but it doesn’t contain most of the services and other function like YouTubeService, YouTubeServiceEvent, com.adobe.webapis package…)

  10. Mark Murphy says:

    DevGirl,
    Great blog. I like the tone and helpfulness. Hope you can fix those links though :-)

  11. craig says:

    Hi Holly, Can you clarify how to correctly put the API in on Flash Builder 4.5 as I’m unsure where it should go and gettingan error below

    Many thanks

    Craig

    Description Resource Path Location Type
    1046: Type was not found or was not a compile-time constant: YouTubeServiceEvent. VideoJuice.mxml /VideoJuice/src line 26 Flex Problem

  12. FYI to all – I’ve posted the original samples and source to my blog here at http://devgirl.org/files/YouTubeSample/

    We will be updating Tour de Flex this week with them as well.

    Thanks!!
    Holly

  13. Lior says:

    Thanks Holly!!!

  14. Ahmad says:

    how to change the youTube logo in video in youtube flex api

  15. Ahmad says:

    HI ,
    I want to remove the “youtube” icon in you tube player as we are using youtube API in flex

  16. Rodrigo says:

    Hi,

    i would like to know if is possible use youtube api for flex on iOS. I’m tryng without success.

    Thanks a lot.

  17. Hardik says:

    will u plese help me for twitter login via flex…
    mean like a tweetdeck….
    i m lookin for sample code

  18. Irfan says:

    Hey, thx on very good examples, I was wondering if it is possible to create playlist and save it through flex app…. Does the api support something like that, and if not, is it feasible at all?

  19. Alejandro says:

    Hi Holly, thanks for the app, and also for taking the time teach folks like us, i was trying the code on my pc, and i found that it does play most of videos, but when i try to play a music video clip it does not load, however it does load live music videos, which i thought was wired, can you think of any possible cause for this?

    Thanks and best regards

  20. Alejandro says:

    Hi Holly, thanks for the app, and also for taking the time teach folks like us, i was trying the code on my pc
    , and i found that it does play most of videos, but when i try to play a music video clip it does not load, however it
    does load live music videos, which i thought was wired, can you think of any possible cause for this?

    Thanks and best regards

  21. shana says:

    I have some problems with the youtube API
    i’m building an application that shows youtube results (in text) after entering a keyword and it also embeds a player.

    There is an option for dragging these items to a “favorite list”

    the problem is that the video doesn’t load when i click on one of the items. Can you please help?

    It is possible to email the code cause it is quite a lot

    Thanks in advance!

  22. Gva says:

    Frst of all thnx holly….. its suberb try… hats of to ur try…. i have a small doubt regarding that holly…..

    i’m not able to play all videos , when i was click on the datagrid…. i able to play some videos only…. i dont know what was the isssue…. can you explain it?…. pls…. i really want it…..

  23. elyes says:

    first i want to say thinks for all explanation an sweet tutorial(specially for mobile),
    then i wondered if i can use the player in a flex mobile application (the video displayer is not customized for mobile application), there are other methods?

  24. Andrew says:

    Hi!
    I have error: Access of undefined property JSON.
    Why?

Leave a Reply