Playing a YouTube Video in an ASP.NET Application

Introduction

Embedding Video Players using pure HTML5 video technology can enhance Web page aesthetics and overall user experience. YouTube is the most popular video sharing websites in the world. That’s why, as with many popular Google services, YouTube also has a Data API. The YouTube API allows developers to interact with this service. By using this API, developers can query videos, search videos, and upload videos on YouTube.

In this article, I will demonstrates the coding technique for playing a YouTube video using an embed link. I will also demonstrate an example to consume the YouTube API to get a list of videos from a channel.

Playing Embedded YouTube Videos in ASP.NET MVC

YouTube allows developers to retrieve the embed code of a video published in a YouTube channel. To get the embed code, you need to visit YouTube and find a video which you want to display. Copy the URL which is displayed in the browser address bar.

The following URL is a sample embedded YouTube video link: https://www.youtube.com/watch?v=xNhuA4aR2XQ.

To demonstrate the YouTube embed video feature from ASP.NET, I have created an MVC application from Visual Studio.

In the MVC application, I have appended the ID of the YouTube video with YouTube embed video URL, which is ultimately assigned to HTML IFRAME element in ASP.NET MVC Razor.

In the MVC View, I have added an HTML TextBox, a Button, and an IFRAME element.

The Button has been assigned to a jQuery click event handler. During the Button click event, first the YouTube Video URL will be fetched from the TextBox, and then YouTube Video ID is extracted from the URL.

The preceding extracted YouTube Video ID will be appended to the YouTube embed video URL. Finally, the URL is set to the SRC property of the HTML IFRAME element for audience view. The following code snippet explains the HTML view.

@{
   Layout = null;
}
<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width" />
   <title>Sample YouTube Embed Video Example</title>
</head>
<body>
   <input type="text" id="YoutubeUrl" style="width:300px" />
   <input type="button" id="PlayVideo" value="Play" />
   <hr />
   <iframe id="YouTubevideo" width="420" height="315"
      frameborder="0" style="display:none"
      allowfullscreen></iframe>
   <script type="text/javascript"
      src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3
      /jquery.min.js"></script>
   <script type="text/javascript">
      $("body").on("click", "#PlayVideo", function () {
         var url = $("#YoutubeUrl").val();
         url = url.split('v=')[1];
         $("#YouTubevideo")[0].src = "//www.youtube.com/embed/" +
            url;
         $("#YouTubevideo").show();
      });
   </script>
</body>
</html>

The following MVC Controller code consists of an Action method named Index. Inside this Action method code, I have simply returned the View.

public class HomeController : Controller
{

   public ActionResult Index()
   {
      return View();
   }
}

Consuming the YouTube API

Google provides a YouTube Data API. This API allows developers to interact with the YouTube service and create various applications. To interact with YouTube API, you have to create a key.

To create a Google API key, follow these steps.

Step 1

You need to create an account in Google if you don’t have one already. Once the account is created, next you should navigate to Google Developers Console Web site, as shown in Figure 1.

Enabling the YouTube Data API
Figure 1: Enabling the YouTube Data API

Next, you should create a new project. I have already created a project named ‘MyCoolProject’ shown in the previous example.

Next, click the “Enable” button. This will lead you to a new page where you can enable all needed APIs.

Step 2

On the next page, enable “YouTube Data API v3” and “YouTube Analytics API.” In Figure 2, you can see YouTube Data API v3 is enabled.

YouTube Data API Statistics
Figure 2: YouTube Data API Statistics

Step 3

Generate the API key by clicking the ‘Credentials’ link. We will use the generated API Key in code (see Figures 3 and 4).

Generating a Data API Key
Figure 3: Generating a Data API Key

Data API Key Generated
Figure 4: Data API Key Generated

Step 4

Now, Create an ASP.NET MVC application from Visual Studio. Open NuGet Console and search for “Google.Apis.YouTube.v3.’ Install that package, as shown in Figure 5.

Installing the 'Google.Apis.YouTube.v3' NuGet Package
Figure 5: Installing the ‘Google.Apis.YouTube.v3’ NuGet Package

Once all packages are installed, the following Google and YouTube specific assemblies will be added to the reference folder (see Figure 6).

References are added in the Project
Figure 6: References are added in the Project

Step 5

Next, create a new class, YouTubeVideo, and add it to the YouTube API.

The following GetVideos function is added to the YouTubeVideo class that returns all the videos (objects of the MyYouTubeVideoObject class) of a specific channel. I have used the API created in the previous step for calling the YouTube API.

namespace YouTubeAPISample
{
   public class MyYouTubeVideoObject
   {
      public string VideoId { get; set; }
      public string Title { get; set; }
   }
   public class YouTubeVideo
   {
      const string MYYOUTUBE_CHANNEL = "SampleChannel";
      const string MyYOUTUBE_DEVELOPER_KEY =
         "AIzaSyDsCC8-hnOokLB2qsBq3WnJXQ_9poKOBus";

      public static MyYouTubeVideoObject[] GetVideos()
      {
         YouTubeRequestSettings settings =
            new YouTubeRequestSettings("SampleChannel",
            MyYOUTUBE_DEVELOPER_KEY);
         YouTubeRequest request = new YouTubeRequest(settings);
         string feedUrl = String.Format
            ("http://gdata.youtube.com/feeds/api/users/{0}
            /uploads?orderby=published", MYYOUTUBE_CHANNEL);
         Feed<Video> videoFeed = request.Get<Video>
            (new Uri(feedUrl));
         return (from video in videoFeed.Entries
         select new MyYouTubeVideoObject()
         { VideoId = video.VideoId, Title = video.Title })
            .ToArray();
      }

   }
}

Conclusion

I hope this article explains how to interact with the YouTube service to display videos from a YouTube channel. You can use the the preceding codebase to display a video list in your Web site. The YouTube data API provides a rich set of features to interact with YouTube. That’s all for today. Happy coding!

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read