Search code examples
c#xamluwpwindows-store-apps

MediaPlayerElement don't play sound on Pc, but does on Phone


I have set a MediaPlayerElement in the XAML, and I play some sounds from Music folder, It works when I test it on The phone, but not on my computer with this error message:

Error: Unsupported video type or file path

I have google it around for a while, some suggestions said that the app should be installed to be able to access files (like the Music file)

This is the XAML:

<MediaPlayerElement Name="mediaPlayerElement" AutoPlay="False" AreTransportControlsEnabled="True" Stretch="UniformToFill"/>

As for the C#:

private void playSound(object sender, ItemClickEventArgs e)
        {// triggered when I click a sound
            var soundToPlay = (Sound)e.ClickedItem;
            mediaPlayer.Source = MediaSource.CreateFromUri(new Uri(this.BaseUri, soundToPlay.Path.ToString()));
            mediaPlayerElement.SetMediaPlayer(mediaPlayer);;
        }
public class Sound
    {
        public string Title { get; set; }
        public string Path { get; set; }
        public string Duration { get; set; }
        public ImageSource Poster { get; set; }
    }// and there is a class to get List<Sound>

When I debugged this code; It turns out that

soundToPlay

points to the exact location of the sound!


Solution

  • The error info is saying "Unsupported video type or file path", so first of all, the workaround for this issue is to using storagefile instead of path:

    mediaPlayer.Source = MediaSource.CreateFromStorageFile(videoFile);
    

    And actually we need to avoid using path. UWP using StorageItems classes (i.e. StorageFolder and StorageFile) which has full privilege to files through a broker process. It represent a file but it is not restricted to file system objects,the app deals with the StorageFile and doesn’t need to know or care if the data originated on disk or in another app. In this way, your working with files are more easier.