Tuesday, August 31, 2010

Play Youtube Video Using C#

To play Youtube videos in C#, we use the Windows Media Player Control, as already in the post play mp3 - files.
The control can be added to the toolbox, by right clicking  on it and then selecting "Select Element ...". In the upcoming window switch to COM controls and then select Windows Media Player.
The multimedia file which is to be played can be set via the property URL. Now one can just put the address of the Youtube video as URL and the media player plays the video on the C# form. But the direct path to the video and not the URL address, on which the video is viewed online, has to be used.
Instead the infix "watch?v=" "/v/" thus has to be used, which describes the folder, in which the Youtube videos are palced. Furthermore, in the video Embedding may not be activated.

An example:

In the brower a video is viewable through the link "http://www.youtube.com/watch?v=8EbtaLNHluE", but the control needs the link "http://www.youtube.com/v/8EbtaLNHluE".
The following code then loads the video in the media player, the video then can be started by clicking "Play" in the video window:

axWindowsMediaPlayer1.URL = "http://www.youtube.com/v/8EbtaLNHluE";

The following example function changes the URL automatically, meaning she gets the online link as input and then plays it:

private void PlayVideo(string url)
{
    axWindowsMediaPlayer1.URL = url.Replace("watch?v=""/v/");
}

2 comments: