Load and Play Media Files at Runtime using Silverlight 2

Posted by: Suprotim Agarwal , on 10/19/2008, in Category Silverlight 2, 3, 4 and 5
Views: 30323
Abstract: There have been quite a few breaking changes from Beta 2 to the final release of Silverlight. One of these changes affects Silverlight 2 application using the OpenFileDialog. In this short article, we will study these changes and explore how to load and play media files at runtime using the OpenFileDialog control using the final release of Silverlight 2.
Load and Play Media Files at Runtime using Silverlight 2
 
Sometime back, I had written a similar article Load and Play a Video File at Runtime using Silverlight 2 Beta 2. The article made use of the OpenFileDialog class in Silverlight Beta2 to load files at runtime. There have been quite a few breaking changes from Beta 2 to the final release of Silverlight. One of these changes affects Silverlight 2 application using the OpenFileDialog. In this short article, we will study these changes and explore how to load and play media files at runtime using the OpenFileDialog control using the final release of Silverlight 2.
Note: I hope you have upgraded your development environment from Silverlight Beta 2 to the final release of Silverlight 2. If you have not yet done so, I would suggest you to read my post: Silverlight 2 Beta 2 TO Silverlight 2 Final Release - A Complete Step By Step Guide for Upgrading your Development Environment
Before moving ahead, there are a couple of changes related to the OpenFileDialog that you should note if you are upgrading your Silverlight applications from Beta 2 to Final:
-      The System.Windows.FileDialogFileInfo type no more exists. Its functionality is now being exposed via its base System.IO.FileInfo type.
-      In Beta 2, System.Windows.Controls.OpenFileDialog exposed FileDialogFileInfo through some properties. These properties were modified and in the final release of Silverlight, they now return the FileInfo type.
-       The property names ‘SelectedFile’ and ‘SelectedFiles’ have been changed to ‘File’ and ‘Files’.
With this information in hand, let us re-build our sample
Step 1: Open Visual Studio 2008 > File > New Project > Select the language (C# or VB) > Select ‘Silverlight’ in the Project Types > from the templates, select ‘Silverlight Application’. Type a name ‘RuntimeMedia’ (for VB.NET users - RuntimeMediaVB) and location for the project and click ok.
Note: If you are unable to view the templates, you do not have Microsoft Silverlight Tools for Visual Studio 2008. Check out this link to see how to obtain it.
Step 2: You will observe that a default page called ‘Page.xaml’ gets created. Set the Width and Height of the user control to 600 & 500 respectively. Remove the <Grid> and replace it with <Canvas> and set its background to Gray. The code after these changes will look similar to the following:
<UserControl x:Class="RuntimeMedia.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/
presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="600" Height="500">
    <Canvas Background="Gray" >
 
    </Canvas>
</UserControl>
 
Step 3: Now add a <MediaElement> and a <Button> Control. After setting the height and width of the MediaElement and and a few additional properties of the Button control, the code will look similar to the following:
    <Canvas Background="Gray" >
        <MediaElement x:Name="mediaEle" Height="440" Width="600"></MediaElement>
        <Button x:Name="btnShow" Click="btnShow_Click" Height="50" Width="100" Canvas.Top="450" Content="Load Media"></Button>       
    </Canvas>
Notice the Event Handler btnShow_Click. We will use this event to code the functionality to select media files at runtime.
Step 4: We will be using the OpenFileDialog class to select media files at runtime. Once the user has selected the file, we will play the selected files.
Go to the code behind (Page.xaml.cs or Page.xaml.vb) and write the following code. You also need to reference the namespace System.IO:
C#
        private void btnShow_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = "Media WMV|*.wmv";
            if (fileDialog.ShowDialog() == true)
            {
                FileInfo fdfi = fileDialog.File;
                mediaEle.SetSource(fdfi.OpenRead());
                mediaEle.AutoPlay = true;
            }
        }
VB.NET
    Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim fileDialog As OpenFileDialog = New OpenFileDialog()
        fileDialog.Filter = "Media WMV|*.wmv"
        If fileDialog.ShowDialog() = True Then
            Dim fdfi As FileInfo = fileDialog.File
            mediaEle.SetSource(fdfi.OpenRead())
            mediaEle.AutoPlay = True
        End If
    End Sub
In the code above, we are creating an instance of the OpenFileDialog and specifying the file filter string by setting the Filter property to "Media WMV|*.wmv". We then call the ShowDialog method to show the open file dialog box to the user. When the method returns, we test to see if the user pressed the OK button (fileDialog.ShowDialog() == true). If the result is True, we use fileDialog.File to return an object of the FileInfo type. The SetSource() method of the MediaElement is used to set its source to the supplied stream using the FileInfo object. The ‘AutoPlay’ property plays the media as soon as it is loaded.
That’s it. Run the application and check out the functionality to add and play video files at runtime. I hope you liked the article and I thank you for viewing it.
 If you liked the article,  Subscribe to my RSS Feed.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by keith on Thursday, April 16, 2009 10:13 AM
I have coded this scenerio in my app as a test.  This comment is a possible expansion for your blog, should you find it a worth while topic.

What I am trying to get to is having the .wmv files stored in sqlServer.  I dont want to store large amounts of .wmv files with the app. I currently have a WebServiice coded to deliver images to the app.  Now I would like to do the same for the .wav.  When the user clicks a button, retrieve that data, open a new browser session, and run the .wmv there.  Its a help function, so I want them to be able to run it .. pause ..  do something in the app .. back to the other window .. etc.

Let me know if you do. Or if you know of a link to something similar. Im curretly trying to figure this out.  I am at about square 1 on this (like what kind of db field and control to store the .wav data), thats how I found your blog.
Comment posted by Suprotim Agarwal on Friday, April 17, 2009 6:10 AM
Keith: Storing a .wav in the db is not a very good idea. Infact you can store the file on the filesystem and add that path to the DB.

Having said that, if you want to store the .wav in the DB, you would need to convert the file to a byte array and then store it. Check these two articles of mine for clues

Save and Retrieve Images from the Database using ASP.NET
http://www.dotnetcurry.com/ShowArticle.aspx?ID=129

Display Images from a Database in a Silverlight DataGrid Control
http://www.dotnetcurry.com/ShowArticle.aspx?ID=264
Comment posted by sivakuamr on Wednesday, July 29, 2009 2:37 AM
Hello sir,
            My video name is Bear.wmv..where i will put this video..

private void btnShow_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = "Media WMV|*Bear.wmv";
            if (fileDialog.ShowDialog() == true)
            {
                FileInfo fdfi = fileDialog.File;
                mediaEle.SetSource(fdfi.OpenRead());
                mediaEle.AutoPlay = true;
            }
        }

Error   1   The type or namespace name 'FileInfo' could not be found (are you missing a using directive or an assembly reference?)   C:\Inetpub\wwwroot\SilverlightApplication7\Page.xaml.cs   28   17   SilverlightApplication7

Error   2   Copying file C:\Inetpub\wwwroot\SilverlightApplication7\Bin\Debug\SilverlightApplication7.xap failed. Could not find file 'C:\Inetpub\wwwroot\SilverlightApplication7\Bin\Debug\SilverlightApplication7.xap'.   SilverlightApplication7.Web

Comment posted by sivakumar on Wednesday, July 29, 2009 8:24 AM
what is the difference between Grid and canvas control
Comment posted by Suprotim Agarwal on Thursday, July 30, 2009 3:25 AM
siva: Make sure you have referenced the namespace System.IO
Comment posted by shiva on Thursday, July 30, 2009 10:22 AM
when i will click button in runtime directly run the video...

private void btnShow_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = "Media WMV|*Bear.wmv";
            if (fileDialog.ShowDialog() == true)
            {
                FileInfo fdfi = fileDialog.File;
                mediaEle.SetSource(fdfi.OpenRead());
                mediaEle.AutoPlay = true;
            }
        }
so where can i specify my path name......plz correct the code....
Comment posted by shiva on Tuesday, August 4, 2009 4:26 AM
hi,

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

plz expalin this code...wat is the use.............
Comment posted by Suprotim Agarwal on Wednesday, August 5, 2009 3:54 AM
Shiva: The first one is the default namespace for XAML files. There is a secondary namespace http://schemas.microsoft.com/winfx/2006/xaml named "x" and should be used for some declaration and classes that aren’t available in default namespace.
Comment posted by Sumit on Wednesday, February 10, 2010 6:36 PM
Thanks Suprotim, helped me build an ol' file uploader solution I found on the internet! Currently looking for Multiple File Upload functionality (for free ;-) )...
Comment posted by Suprotim Agarwal on Saturday, February 13, 2010 12:25 AM
Sumit: Thanks mate! I wrote an article on uploading multiple files using jQuery
http://www.dotnetcurry.com/ShowArticle.aspx?ID=317
Comment posted by Lokesh on Monday, December 20, 2010 3:28 AM
Good one.. Working fine in my website...

How to display Pause/Stop/Slider bar ?

many thanks for the nice article.
Comment posted by Lokesh on Tuesday, December 21, 2010 6:05 AM
MainPage.xaml: (silverlight)

<MediaElement MediaFailed="MyMediaElement_MediaFailed" MarkerReached="MyMediaElement_MarkerReached" MediaEnded="MyMediaElement_MediaEnded" MediaOpened="MyMediaElement_MediaOpened" CurrentStateChanged="MyMediaElement_CurrentStateChanged" x:Name="MyMediaElement" AutoPlay="False" HorizontalAlignment="Center" VerticalAlignment="Center" Source="Idealcoachforourteam.wmv"/>

Source="Idealcoachforourteam.wmv" - how to change this attribute value dynamically from aspx .vb/.cs file? (becoz video filename is present in the database)

Regards
Lokesh