Configure Audio Session for background audio mode (iOS Project)

Posted by

We use AVPlayer from AVFoundation to play audio in our applications. The moment we send the application to back ground mode, audio stops playing.

To fix this, we will need to configure AVAudioSession properly. We start by importing AVFoundation in AppDelegate or our iOS Project.

import AVFoundation

Next, add the following code in application didFinishLaunchingWithOptions:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // enable playback category: this is required for background audio to function normally
    let audioSession = AVAudioSession.sharedInstance()
    try? audioSession.setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault)
    try? audioSession.setActive(true, with: [])
    
    return true
}

Finally, enable Background Audio Mode in Project Settings.
Enable background audio mode in XCode Project Settings

Here is gist for the example

// https://hashaam.com/2017/06/15/configure-audio-session-for-background-audio-mode-ios-project/
import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// enable playback category: this is required for background audio to function normally
let audioSession = AVAudioSession.sharedInstance()
try? audioSession.setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault)
try? audioSession.setActive(true, with: [])
return true
}
}

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s