This sample shows how to use a helper class to control the playback of sound using an AVAudioPlayer.

About the AVAudioPlayer

The AVAudioPlayer is used to playback audio data from either memory or a file. Apple recommends using this class to play audio in your app unless you are doing network streaming or require low latency audio I/O.

You can use the AVAudioPlayer to do the following:

Play sounds of any duration with optional looping.

Play multiple sounds at the same time with optional synchronization.

Control volume, playback rate and stereo positioning for each sounds playing.

Support features such as fast forward or rewind.

Obtain playback level metering data.

AVAudioPlayer supports sounds in any audio format provided by iOS, tvOS and OS X such as .aif, .wav or .mp3.

Recipe

First, create a Single View Application for Xamarin.iOS and call it AVAudioPlayerSounds. Add a Sounds folder to the project and add a few sounds files to the folder (ensure to select BundleResource as the Build Action):

Next, add a Classes folder to the project and add a new GameAudioManager class to the folder and make it look like the following:

In this method we first check to see if music playback is allowed and we stop any currently playing background music. Next, we configure the audio playback and load the given audio file from the Sounds directory we created above.

By setting the NumberOfLoops property to -1, we are telling the AVAudioPlayer to loop the song indefinitely.

We have also added methods to StopBackgroundMusic, SuspendBackgroundMusic and RestartBackgroundMusic.