Search code examples
c#silverlight-4.0media-player

Silverlight MediaElement, choosing local disc file


I'm trying to make a Media Player where you can choose either to render a file from url or local disc. I had no problem making it to open and render url file

void LoadVideo_Click(object sender, RoutedEventArgs e)
        {
            LoadVideo.IsEnabled = false;
            mediaElement.Source = new Uri(path, UriKind.Absolute);

With string path = "http://www.blablabla.com/movie.wmv"

The problem occurs when I'm trying to specify local disc file path(as "c:\movie.wmv" or @"c:\movie.wmv"). It simply doesn't work that way.

As far as I have read, you don't have direct access to files on your hard drive besides those which already are in the project directory. What I want to do is:

  • use Dialog Box to choose a file to open
  • save the path of file into string and transfer it to MediaElement.Source

Unfortunately, I don't have a clue how to do it. I would be grateful for any advices.


Solution

  • Here you go, this should do the trick:

            OpenFileDialog fdlg = new OpenFileDialog(); //you need to use the OpenFileDialog, otherwise Silverlight will throw a tantrum ;)
            fdlg.Filter = "MP4 Files|*.mp4|AVI files|*.avi"; //set a file selection filter
    
            if (fdlg.ShowDialog() != true) //ShowDialog returns a bool? to indicate if the user clicked OK after picking a file
                return;
    
            var stream = fdlg.File.OpenRead(); //get the file stream
            //Media is a MediaElement object in XAML
            Media.SetSource(stream); //bread and butter
    
            Media.Play(); //no idea what this does
    

    Here's an extensive example on how to use the OpenFileDialog. As for the MediaElement, you can see in the code above all you needed was the SetSource() method (as opposed to the Source property).