Sunday, March 11, 2012

YouTube Video Play with SharePoint
[Bind YouTube thumbnails, Playing video with popup - Web part] 
There was a requirement to create web part (so called webTV ),in my first SharePoint project @ Navantis. Our client wants to show their videos which has been uploaded to the YouTube. web part should be nice looking with rotating options and it should bind with YouTube video thumbnail.
Rotating part can be done through some of JQueries you can get many examples from the internet on that. this is what we based on http://sorgalla.com/projects/jcarousel/examples/static_simple.html .

First Step ...
First step of creating Rotating panel was not that much hard. all you need to do is get all the required JS files and upload the in to the Style Library and link the with master page.

Second Step ...
we have to create a list which hold YouTube links and if required customized titles and descriptions . Then administrators can update related video links then the related videos can be watched through the web part.

Next Challenge (How to get Video thumbnail)...

In YouTube every video which has been uploaded. contain with several thumbnails (actually it contain with four thumbnails).
it has main thumbnail called zero jpg with a good resolution compare to others. and other images called 1 2 and 3 JPGs related to the video flash points.
YouTube thumbnail form with following address.
https://img.youtube.com/vi/"YouTube Video ID"/0.jpg ('0' can be as 1 2 or 3).

Flowing video view address is : http://www.youtube.com/watch?v=s12Jb5Z2xaE and it's video ID is 's12Jb5Z2xaE'


So by default it contain following images:
Zero Image : https://img.youtube.com/vi/s12Jb5Z2xaE/0.jpg

so as you can see zero image is the main one so all we need to do extract the video id from the link and form the image URLs and bind them with our control. 

How to Extract YouTube Video ID .... 

I have written a method for that with Reg-ex function. through following method you can extract the Video ID with any given Utube video link. 

private string GetYouTubeID(string youTubeUrl)
        {
            //RegEx to Find YouTube ID
            Match regexMatch = Regex.Match(youTubeUrl, "^[^v]+v=(.{11}).*",
                               RegexOptions.IgnoreCase);
            if (regexMatch.Success)
            {
                return regexMatch.Groups[1].Value;
            }
            return null;
        }


What's NEXT .... 
Then I wrote following function to bind all the required data into the repeater of the Web TV control . 

private DataTable GetWebListData()
        {
            DataTable retValue = null;

            if (SPContext.Current.Web != null)
            {
                SPWeb rootWeb = SPContext.Current.Web;
// Get the required list object and assigned it to the SPList [LIST_NEME is the nae of the link list which hold youtube links]
                SPList list = rootWeb.GetListFromUrl(string.Format("{0}{1}{2}{3}", rootWeb.Url, "/Lists/", LIST_NAME, "/AllItems.aspx"));
                SPQuery query = new SPQuery();

                // Order the items by the Index field of the list.
                query.Query = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE' /></OrderBy>";
                SPListItemCollection items = list.GetItems(query);

                retValue = new DataTable();
                retValue.Columns.Add("TargetURL");
                retValue.Columns.Add("PictureURL");
                retValue.Columns.Add("Description");

                foreach (SPListItem item in items)
                {
                    if (item[item.Fields.GetFieldByInternalName("URL").Id] != null)
                    {
                        string YouTubeVideoID = this.GetYouTubeID(item[item.Fields.GetFieldByInternalName("URL").Id].ToString());
                        if (!string.IsNullOrEmpty(YouTubeVideoID))
                        {
                            DataRow row = retValue.NewRow();
 // Here I create URL for embed YouTube video (which required for player), autoplay=1 means play as soon as get loaded with out waiting for user clicks play button.
                            row["TargetURL"] = "https://www.youtube.com/v/" + YouTubeVideoID + "&autoplay=1";
// Here I create URL for embed YouTube video (which required for player).
                            row["PictureURL"] = "https://img.youtube.com/vi/" + YouTubeVideoID + "/0.jpg";
                            row["Description"] = string.IsNullOrEmpty(item.DisplayName) ? "" : item.DisplayName;
                            retValue.Rows.Add(row);
                        }
                    }


                }


            }
            return retValue;
        }


please refer the following Tags which taken from related aspx file. The are which highlighted in yellow is responsible for rotating the control (I have user J Query for that.).
<script>

    $(document).ready(function () {
        //rotation speed and timer   
        var speed = 5000;
        var run = setInterval('rotate()', speed);

        var item_width = $('#WebTvslides li').outerWidth();
        var left_value = item_width * (-1);

        //move the last item before first item, just in case user click prev button
        $('#WebTvslides li:first').before($('#WebTvslides li:last'));

        //set the default item to the correct position
        $('#WebTvslides ul').css({ 'left': left_value });

        //if user clicked on prev button
        $('#WebTvprev').click(function () {

            //get the right position           
            var left_indent = parseInt($('#WebTvslides ul').css('left')) + item_width;

            //slide the item           
            $('#WebTvslides ul:not(:animated)').animate({ 'left': left_indent }, 200, function () {

                //move the last item and put it as first item             
                $('#WebTvslides li:first').before($('#WebTvslides li:last'));

                //set the default item to correct position
                $('#WebTvslides ul').css({ 'left': left_value });

            });

            //cancel the link behavior           
            return false;

        });
        //if user clicked on next button
        $('#WebTvnext').click(function () {

            //get the right position
            var left_indent = parseInt($('#WebTvslides ul').css('left')) - item_width;

            //slide the item
            $('#WebTvslides ul:not(:animated)').animate({ 'left': left_indent }, 200, function () {

                //move the first item and put it as last item
                $('#WebTvslides li:last').after($('#WebTvslides li:first'));

                //set the default item to correct position
                $('#WebTvslides ul').css({ 'left': left_value });

            });

            //cancel the link behavior
            return false;

        });


    });

    //a simple function to click next link
    //a timer will call this function, and the rotation will begin :)
    function rotate() {
        $('#WebTvnext').click();
    } 
        
</script>
<!--/Video Scripts-->
<script>
    $(document).ready(function () {
        //Examples of how to assign the ColorBox event to elements

        $(".youtube").colorbox({ iframe: true, innerWidth: 425, innerHeight: 344 });
        $(".callbacks").colorbox({
            onOpen: function () { alert('onOpen: colorbox is about to open'); },
            onLoad: function () { alert('onLoad: colorbox has started to load the targeted content'); },
            onComplete: function () { alert('onComplete: colorbox has displayed the loaded content'); },
            onCleanup: function () { alert('onCleanup: colorbox has begun the close process'); },
            onClosed: function () { alert('onClosed: colorbox has completely closed'); }
        });

        //Example of preserving a JavaScript event for inline calls.
        $("#click").click(function () {
            $('#click').css({ "background-color": "#f00", "color": "#fff", "cursor": "inherit" }).text("Open this window again and this message will still be here.");
            return false;
        });
    });
</script>
<!--/Video Scripts-->
<div class="wp_marginRight10">
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td align="center" valign="middle" class="vp_left">
                <a href="#" id="WebTvprev">
                    <img alt="" src='<asp:Literal runat="server" Text="<%$SPUrl:~sitecollection/Style Library/Images/NavantisIntranet/al.png %>" />' /></a>
            </td>
            <td class="vp_middle wp_videoImg">
                <div id="WebTvslides">
                    <ul>
                        <asp:Repeater ID="repeaterWebTV" runat="server">
                            <ItemTemplate>
                                <li><a class='youtube' href='<%# Eval("TargetURL").ToString() %>' title='<%# Eval("Description").ToString() %>'>
                                    <img src='<%# Eval("PictureURL").ToString() %>' alt="slide1" /></a> </li>
                            </ItemTemplate>
                        </asp:Repeater>
                    </ul>
                    <asp:Label ID="LabelError" runat="server"></asp:Label>
                    <div class="WebTvclear">
                    </div>
                </div>
            </td>
            <td align="center" valign="middle" class="vp_right">
                <a href="#" id="WebTvnext">
                    <img alt="" src='<asp:Literal runat="server" Text="<%$SPUrl:~sitecollection/Style Library/Images/NavantisIntranet/ar.png %>" />' />
                </a>
            </td>
        </tr>
    </table>
</div>


The Are which highlighted on Green is responsible for playing YouTube video with nice looking popup . Also you can see the repeater which hold the image and other required object. for the control . 

[for this you need to upload some JS and CSS files to style library and set their paths in side the master page.
JS:
jquery.jcarousel.min.js 
jquery.colorbox.js

CSS : 
SponsorsScroll.css
colorbox.css

(Download required files from : http://www.sendspace.com/file/1bdb5q )

Path Tags : 
<script type="text/javascript" src="/Style Library/Scripts/jquery.jcarousel.min.js"></script>
<script src="/Style Library/Scripts/jquery.colorbox.js"></script>
<link href="/Style Library/en-us/Core Styles/SponsorsScroll.css" rel="stylesheet"
    type="text/css" />
<link href="/Style Library/en-us/Core Styles/colorbox.css" rel="stylesheet" type="text/css" />


]

FINAL RESULT .... 






ok That's It ... 
HAPPY CODING
  

No comments:

Post a Comment