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:
- To play a sound from included resources or a
Uri
instance, we use the staticCreate()
method onMediaPlayer
:var mediaPlayer = MediaPlayer.Create( this, Resource.Raw.SoundResource);
- 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; };
- To begin playing, either from a paused or prepared ...
Get Xamarin Mobile Development for Android Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.