How to Play Audio in Background With Swift

How to play audio in background with Swift?

You need to set your app Capabilities Background Modes (Audio and AirPlay) and set your AVAudioSession category to AVAudioSessionCategoryPlayback and set it active

From Xcode 11.4 • Swift 5.2

do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])
print("Playback OK")
try AVAudioSession.sharedInstance().setActive(true)
print("Session is Active")
} catch {
print(error)
}

Sample Image

I cannot play music in the background (Xcode 9, Swift 4)

After spending a couple of days on this issue, I finally figured it out. In swift 4, I think we need to add a couple of lines of code to the appDelegate class under the project directory. Like this:

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.
let session = AVAudioSession.sharedInstance()
do{
try session.setActive(true)
try session.setCategory(AVAudioSessionCategoryPlayback)
} catch{
print(error.localizedDescription)
}
return true
}

func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}

Update: Swift 4.2


This helped also for me:


1. First step:

Sample Image


2. Second:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

let session = AVAudioSession.sharedInstance()
do{
try session.setActive(true)
try session.setCategory(.playback, mode: .default, options: .defaultToSpeaker)
} catch{
print(error.localizedDescription)
}
return true
}

iOS app does not play audio while background

You need to set your app Capabilities Background Modes (Audio and AirPlay) and set your AVAudioSession category to AVAudioSessionCategoryPlayback and set it active.
Please Refer to this link below :
How to play audio in background with Swift?

How to play sounds in iOS 10 when app is in the background with Swift 3

You cannot play in the background with an Ambient audio session category. Your category must be Playback.

To allow sounds from other apps to play, modify your Playback category with the Mixable option (.mixWithOthers).

(Also keep in mind that you can change your category at any time. You could have it be Ambient most of the time but switch to Playback when you know you're about to go into the background so that you can keep playing.)

EDIT Also it occurs to me that there is another possible misconception that might need clearing up. You cannot (easily) start a new sound while in the background. All that background audio allows you to do is continue playing the current sound when your app goes into the background. Once that sound stops (in the background), your app suspends and that's the end of that.



Related Topics



Leave a reply



Submit