Playing audio in an iOS app consists of two steps:

  1. Creating an Audio session using AVAudioSession class.
  2. Playing the audio using Audio player using AVAudioPlayer class.


We want to play audio in apps even though the background music is running. For that, create a shared audio session. The code for initializing a shared session is shown below.

We use the sharedInstance static method to create the session. And set the category to Ambient. Ambient category suggests that app can function without audio. Further, audio from other apps mixes with your audio.

Create the session when the app starts. Typically, place the code in didFinishLaunchingWithOptions in the AppDelegate class.


AVAudioPlayer class plays the audio. It needs a delegate (for some reason). Without supplying a AVAudioPlayerDelegate, it throws a error. All methods in the delegate are optional.

Retrieve the path of the mp3 file from the main bundle. Create a NSURL object from the file path. Initialize AVAudioPlayer with the URL. And then, supply a delegate.

The play method of AVAudioPlayer plays the audio.

Playing audio in iOS using AVAudioPlayer
Tagged on: