Search code examples
uwpwindows-media-player

UWP MediaPlayerElement doesn't play any sound


I try to play mp3 in an UWP app. In the following simple code it doesn't play any sound and video file. There is no error message. The examples in XAML Controls Gallery work well.

private void Button_Click(object sender, RoutedEventArgs e)
{
    MediaPlayerElement _MediaPlayerElement = new MediaPlayerElement();

    _MediaPlayerElement.Source = MediaSource.CreateFromUri(new Uri("D:/alarm.wav"));

    _MediaPlayerElement.AutoPlay = true;
}

Using FileOpenPicker doesn't make any difference, the file path and name feeding doesn't seem to be the reason. What am I missing?


Solution

  • First, when you created a MediaPlayerElement control in code-behind, you need to add it to the parent panel to show it in the foreground. In this case, it will play.

    In addition, the uri is also incorrect. You can use URI schemes to refer to app files that come from the app's package, data folders, or resources rather than the D drive. If you want to use the full path to play, you can use StorageFile.GetFileFromPathAsync() method or FileOpenPicker to get the file and then pass the file to MediaSource.CreateFromStorageFile() method to set Source.

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MediaPlayerElement _MediaPlayerElement = new MediaPlayerElement();
        //uri
        _MediaPlayerElement.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/xxx.mp3"));
    
        //file path
        //StorageFile file = await StorageFile.GetFileFromPathAsync(@"D:\xxx.mp3");
        //_MediaPlayerElement.Source = MediaSource.CreateFromStorageFile(file);
        _MediaPlayerElement.AutoPlay = true;
    
        MyBigPanel.Children.Add(_MediaPlayerElement);
    }