How to play audio in background with Swift?
Solution 1:
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)
}
Solution 2:
Xcode 10.2.1 Swift 4
Please add the following code in your AppDelegate
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault, options: [.mixWithOthers, .allowAirPlay])
print("Playback OK")
try AVAudioSession.sharedInstance().setActive(true)
print("Session is Active")
} catch {
print(error)
}
return true
}
Note: - Please configure options as required. E.g to stop a background audio while a video file being played add
options: [.allowAirPlay, .defaultToSpeaker]
And don't forget to enable audio and airplay in Background mode
Solution 3:
Only paste on the viewDidload
let path = Bundle.main.path(forResource:"Bismallah", ofType: "mp3")
do{
try playerr = AVAudioPlayer(contentsOf: URL(fileURLWithPath: path!))
} catch {
print("File is not Loaded")
}
let session = AVAudioSession.sharedInstance()
do{
try session.setCategory(AVAudioSessionCategoryPlayback)
}
catch{
}
player.play()
Solution 4:
Swift 5 Xcode 11.2.1
Add this code where you have initialized the AudioPlayer.
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setCategory(AVAudioSession.Category.playback)
}
catch{
fatalError("playback failed")
}