How to play audio in background with Swift? How to play audio in background with Swift? ios ios

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)}

enter image description here


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 modeenter image description here


Only paste on the viewDidload

enter image description here

    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()