O'Reilly logo

Xamarin Mobile Development for Android Cookbook by Matthew Leibowitz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Playing audio

Many apps, especially games, have sounds. This can just be a feedback sound or one that enhances the navigation or interaction of the game. Games usually have background music playing on a loop.

How to do it...

The MediaPlayer type is used to play a sound from a content provider, a URI or a resource:

  1. To play a sound from included resources or a Uri instance, we use the static Create() method on MediaPlayer:
    var mediaPlayer = MediaPlayer.Create(
      this, Resource.Raw.SoundResource);  
  2. Then, because we need to be able to clean up after the sound is finished, we subscribe to the Completion event and release the player:
    mediaPlayer.Completion += delegate {
      mediaPlayer.Release();
      mediaPlayer = null;
    };
  3. To begin playing, either from a paused or prepared ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required