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 state, we invoke the
Start()
method:mediaPlayer.Start();
Finally, we can control the player using the
Pause()
andStop()
methods:mediaPlayer.Pause(); mediaPlayer.Stop();
If we want to stream sound from an asset or a remote URI, we construct...