Videos & Visual Basic.NET Part 2 - YouTube and Flash Videos

Introduction

Hello again. If you have read my previous installment of Videos & VB.NET, you'll have a great understanding of what we will do today. If not, today we will learn how to play Flash Videos and YouTube videos from our VB.NET application. This is sure to be a great deal of fun, so let's start!

Design

Open Visual Studio 2012 and create a Windows based VB.NET application. Our application consists of two forms. Form 1 will view the videos and Form 2 will enable us to search via YouTube for our desired videos.

Form 1

Obviously, you can name it what you want. You need to put the following onto Form1:

  • Menu with the following MenuItems:
    • File
      • Search on PC...
      • Search on YouTube
      • Exit
    • Player
      • Play
      • Stop
  • ListBox
  • ShockWave Flash Object
    • Right Click inside your Toolbox
    • Select Choose Items...
    • Select AxShockWaveFlash from the list. If it is not there, ensure that you have the latest Flash Player installed on your computer.

Form 2 Needs the following:

  • A TextBox  to enter our query
  • Two buttons - OK and Cancel
  • Set OK button's DialogResult property to OK

YouTube SDK ( Software Development Kit )

You can't jump right in with the code. Why? Well, we first need to download the YouTube SDK and Google Data API. The reason why I say we need to download this is because with all other SDKs we first must learn how to work with the particular technologies - we cannot just copy and paste code without understanding how they work; make sense?

We can download these here.

After you have familiarized yourself with the Googlde GData API and what it can do and browsed through the samples, you'll have a greater understanding of what we will try to accomplish today.

Now, some of you might remember that I created two Facebook applications throughout the years. You're probably thinking why am I bringing up Facebook here? The answer is: in order for us to be able to communicate with Facebook from any of our programs making use of their platform(s) we must have a valid developer key. YouTube and Google are not much different. I think in a previous article utilizing Google Maps, we also had to have a developer key. This key proves to whomever that this application is valid and not trying to do illegal stuff. This is how the programs get tracked at the end of the day, even Android programs need a certain type of developer key.

How do I Get a Google / YouTube Developer Key?

You need to have a valid Google account and then navigate to http://code.google.com/apis/youtube/dashboard/gwt/index.html.

Here you can set up a name for your project and get your key. This key must be present in all your programs using this framework, along with the application name you specified here. This ensures that Google can track your program's calls and usage.

Everything is now set up, so we can now proceed to the code.

Code

As usual, let me start with the Imports we need; add these above your class declaration:

'Import Necessary Youtube & Google Libraries
Imports Google.YouTube 
Imports Google.GData.YouTube
Imports Google.GData.Client
Imports Google.GData.Extensions.MediaRss

These namespaces will aid in doing YouTube searches and manipulating the given results into a readable format.

Add the following Private member variables:

    Private strSettings As YouTubeRequestSettings 'Create New YouTubeRequestSettings Object To Store App, & Key
    Private strRequest As YouTubeRequest 'New YouTubeRequest Object hosting Settings Object

    Private arrVideoIDs() As String 'Array To Hold Vidoe IDs

    Const strAppName = "HTG_Video_2_Youtube_Flash" 'My Application Name
	
	'My Key
    Const strKey = "AI39si76cQbbcpLqbloyRFEXWkC8QPjUYr_g8DbS1ZiUqNbxjkdzieB5x2wVIqR3ELgM5v1qDg66zSXBMHK3bhFCN3E-be2ZWQ"

Here we create a YouTubeRequestSettings object and a YouTubeRequest object. we will use these to identify our program. Our Application name is there as well as our Key. I also created an array that will store all the found YouTube videos, so that we can list them inside a listbox for example.

Add the Form_Load event:

    Private Sub frmFlashYoutube_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        strSettings = New YouTubeRequestSettings(strAppName, "Youtube Example", strKey) 'Store My Details

        strRequest = New YouTubeRequest(strSettings) 'Create New request based On My Details
    
	End Sub

We identify our program and key on startup.

Let us add the File Menu events:

    Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
        
		Application.Exit() 'Exit

    End Sub

    Private Sub SearchOnPCToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SearchOnPCToolStripMenuItem.Click
        
		Dim strFileName As String 'FileName
        
		'Filter For OFD
		ofdOpen.Filter = "FLA Files|*.fla|ShockWave Files|*.swf|All Files|*.*"
        
		strFileName = ofdOpen.FileName 'Browse PC For Suitable Files
        
		If ofdOpen.ShowDialog = Windows.Forms.DialogResult.OK Then 'If Valid File Selected
            
			FlashMedia.LoadMovie(0, strFileName) 'Load
            FlashMedia.Play() 'Play

            PlayToolStripMenuItem.Text = "Pause" 'Change 'Play' To 'Pause'

        End If

    End Sub

    Private Sub SearchOnYoutubeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SearchOnYoutubeToolStripMenuItem.Click
        
		Dim FSearch As New frmSearch 'Initialize Custom Search Form

        If FSearch.ShowDialog = DialogResult.OK Then 'If Valid Search String Entered

            Dim strQuery As String = FSearch.txtSearch.Text 'What Was Entered

            Dim ytsService As YouTubeService = New YouTubeService(strAppName, strKey) 'Create YouTube Service

            Dim urlEntryUrl As Uri = New Uri("http://gdata.youtube.com/feeds/api/videos?q=" + strQuery) 'Search On YouTube

            Dim fqResults As FeedQuery = New FeedQuery() 'Get results

            fqResults.Uri = urlEntryUrl

            Dim vidFeed As Feed(Of Video) = New Feed(Of Video)(ytsService, fqResults) 'Get List Of Videos

            Dim intCounter As Integer 'Count

            For Each vidEntry As Video In vidFeed.Entries 'For Each Video Found

                lstYouTubeResults.Items.Add(vidEntry.Title.ToString) 'Show Title In ListBox

                ReDim Preserve arrVideoIDs(intCounter) 'Store In Array

                arrVideoIDs(intCounter) = vidEntry.Id.ToString 'Get ID

                'Subtract Only Video ID
				arrVideoIDs(intCounter) = arrVideoIDs(intCounter).Substring(arrVideoIDs(intCounter).LastIndexOf(":") + 1)

                intCounter += 1

            Next

        End If

    End Sub

Exit, exits our program.

Search On Pc, enables us to search for a valid Flash file on our pc, then it simply loads it and plays it.

Search on Youtube creates and displays our second form where we can enter our search string. This search string can be anything you'd like to search for inside YouTube.  Figure 1 shows the search screen with my entered text.

`Searching for Creedence Clearwater Revival
Figure 1 - Searching for Creedence Clearwater Revival (One of the best bands ever! )

Our program searches through YouTube by appending our entered text to the http://gdata.youtube.com/feeds/api/videos?q=  URL. This then returns a set of results, which we need to loop through and truncate each item so that we only have the Video name, instead of all the other jargon associated with it. Once we have each videos' name, we list them inside a ListBox, as shown in Figure 2.

Our search results
Figure 2 - Our search results

The tricky part now is to get each video's ID. This is the weird string you usually see in YouTube when playing it. The text might look something like tGWVVdVbnJc. The full URL of a YouTube video looks like http://www.youtube.com/watch?v=tGWVVdVbnJc. Now the last text after v= is the video's ID. The ID is what we need to play, hence our string manipulation of our array.

Once we have proper IDs and the names listed, we can play the video. Let us add the ListBox_SelectedIndexChanged event:

    Private Sub lstYouTubeResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstYouTubeResults.SelectedIndexChanged

		'Get Selected Video And Watch It
        Dim videoID As String = "http://www.youtube.com/watch?v=" & arrVideoIDs(lstYouTubeResults.SelectedIndex)
        
		videoID = videoID.Replace("/watch?v=", "/v/")

        FlashMedia.Movie = videoID

    End Sub

Here we format our video's URL and play it. We know which one to play as the ListBox shows our array arrVideoIDs items.

All we need to do now is add the Play menu item's code:

    Private Sub PlayToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PlayToolStripMenuItem.Click
       
	    If PlayToolStripMenuItem.Text = "Play" Then 'Played

            FlashMedia.Play()
            PlayToolStripMenuItem.Text = "Pause" 'Change to 'Pause'

        Else
            
            PlayToolStripMenuItem.Text = "Play" 'Change To 'Play'

        End If

    End Sub

Conclusion

There you have it! Enjoy your new YouTube video player, as much as I am enjoying mine. Watch for Part 3 of Videos and VB.NET entitled Videos & XNA. Thanks for reading. Hannes



Related Articles

Comments

  • Thanks

    Posted by Hannes on 01/28/2014 03:47am

    Hello Michael. Thank you for your passionate reply. Unfortunately, it seems as if you have not read properly, sorry. The code you are complaining about is stated clearly inside the SearchOnYoutubeToolStripMenuItem_Click event. In there I make use of the search form like : Private Sub SearchOnYoutubeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SearchOnYoutubeToolStripMenuItem.Click Dim FSearch As New frmSearch 'Initialize Custom Search Form If FSearch.ShowDialog = DialogResult.OK Then 'HERE!!!!!! This is the proper way to handle dialogs in any .NET program. You say you are a newbie, so, handling dialogs like I did is hopefully something new to you. On a side note: Your reply is a bit harsh. We all know how frustrating it can be to learn things. But, think first before you blame everyone and even CG. The use of this tutorial ( like all my others ) are to demonstrate how things can be done. All my articles follow the same rules. All my code always work, as it is tested properly before being posted. About newer content : Every week there are quite a few new topics covered on CodeGuru, in all aspects of programming. Have a look around and you'll see, and hopefully learn even more. When reading articles, you should not just simply copy and paste the code - that defeats the whole object of having articles. If you want to learn, you need to make sure to read everything; so that you can see in which context a certain piece of code was used. Thanks again for reading my article, but I assure you, there is nothing wrong with it. I have spent the night following the steps I outlined, and I didn't have issues. Hope to see you around more often, and good luck with your learning! Hannes

    Reply
  • You guys should stop making TUTORIALS

    Posted by Michael on 01/24/2014 10:03pm

    I am so disapointed about the Tutorials on this Site! Most of them are too old and never updated and even if they are new such as this one, its not completed! The OK and CANCLE button has no meaning. Where are rest of the codes for the OK AND CANCLE BUTTON! How do you Proceed a search? You guys should really consider making more tutorials, for you guys are making in hard for other newbies like myself! But thank god I know more than what you guys have presented in this tutorial which us uncomplete! Waste of time!

    Reply
  • Set OK button's DialogResult property to OK

    Posted by Endriu on 10/09/2013 02:30am

    What code use to set this OK button?

    • OK Button

      Posted by Hannes on 01/27/2014 10:21pm

      Thanks for reading Endriu. The code for the OK button is placed inside the SearchOnPCToolStripMenuItem_Click event. Look closely. It is explained in this article.

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Live Event Date: November 13, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT APIs can be a great source of competitive advantage. The practice of exposing backend services as APIs has become pervasive, however their use varies widely across companies and industries. Some companies leverage APIs to create internal, operational and development efficiencies, while others use them to drive ancillary revenue channels. Many companies successfully support both public and private programs from the same API by varying levels …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds