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


Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame


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!


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.


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


        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

            PlayToolStripMenuItem.Text = "Pause" 'Change to 'Pause'

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

        End If

    End Sub


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


  • Mr

    Posted by perfo on 05/19/2016 05:45pm

    Hello, I like the project and I think I know what it's doing. I found it by trying to learn about loading and controlling youtube videos in my application. Unfortunately I think it is a little above my capabilities at the moment and can't find any easier examples. I get far too many errors to list here and wondering it you have an example project I could download and play with ? Thanks for the time and effort in to making this tutorial, If I was more experienced I bet it's exactly what I'm looking for...

  • Imports errors

    Posted by Will on 08/27/2015 01:08pm

    Hi, I am getting an error at the imports section which is saying the namespace is not public or not found. I am wondering if this is because I am using Youtube Data API v3. Does the imports section of the code need to be updated for this new version? I have followed all of the instructions including downloading the Google Data API. This is example is exactly what I am looking for and I would love to get it working, but it is not recognizing these lines: Imports Google.YouTube Imports Google.GData.YouTube Imports Google.GData.Client Imports Google.GData.Extensions.MediaRss

  • Missing code in OK and Cancel buttons

    Posted by Jose Carlos Macoratti on 01/19/2015 01:47pm

    Put the code below in the Click event of Ok Button Me.DialogResult = DialogResult.OK Me.Hide() Put the code below in the Click event of Cancel Button Me.DialogResult = DialogResult.Cancel Me.Hide()

  • Thanks

    Posted by Hannes on 01/28/2014 11: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

  • You guys should stop making TUTORIALS

    Posted by Michael on 01/25/2014 06:03am

    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!

  • Set OK button's DialogResult property to OK

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

    What code use to set this OK button?

    • OK Button

      Posted by Hannes on 01/28/2014 06:21am

      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.

  • You must have javascript enabled in order to post comments.

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

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date