MediaPlayer Universal Windows App

2.3k Views Asked by At

I started to develop application using xamarin, and one of projects inside my solution is UWP.

I need to play sound there when someone clicked button, I'm using MediaPlayer to achieve my goal, and on windows 10 (desktop) it works fine, but on my Windows Mobile 10 (Lumia 930) it starts with long delay (about 1 second).

Below I provide my code to play audio source:

MediaPlayer _player = BackgroundMediaPlayer.Current;
_player.SetUriSource(new Uri(String.Format("ms-appx:///Assets/Sound/5s.wav", UriKind.Absolute)));            
_player.Play();

My Question is:

Is there any other way to play audio in UWP than MediaPlayer?

2

There are 2 best solutions below

1
Konstantin On

If you don't have specific reason to use background audio, you can use just media element to play audio in foreground:

<!-- create element in XAML or in code -->
<MediaElement Name="mediaElement" ... />


// Code - set source or reference to stream
MediaElement mediaElement = new MediaElement();
mediaElement.Source = new Uri("msappx:///Media/sound.mp3");    

I would also recommend to check with the list of supported codecs.

In more complex scenarios you may want to look at Audio Graph API.

0
Evan de la Cruz On

I'm not sure if this is bad practice or not, but I am able to get instant playback if I pre-load the media.

Something like this example in pseudo-code (c# style):

class Foo
{
   private MediaPlayer _player;

    Foo() //constructor
    {
      _player = BackgroundMediaPlayer.Current;
      _player.AutoPlay = false;
      _player.SetUriSource(new Uri(String.Format("ms-appx:///Assets/Sound/5s.wav", UriKind.Absolute)));            
    }

    void ButtonClicked(Object sender, EventArgs event)
    {
        _player.Play();
    }
}