How to play audio in background with Swift?

IosSwiftAudioAvfoundation

Ios Problem Overview


As you see I'm streaming an audio broadcast. But when I press the home button and exit the app streaming stops or I cannot hear. How can I continue streaming in background and listen it from lock screen?

ViewController.Swift

import UIKit
import AVFoundation
import MediaPlayer
import GoogleMobileAds


    class ViewController: UIViewController, GADInterstitialDelegate {
    
        @IBOutlet weak var exitMapButton: UIButton!
        @IBOutlet weak var radarMap: UIWebView!
        var interstitial: GADInterstitial!
        func createAndLoadInterstitial() -> GADInterstitial {
            var interstitial = GADInterstitial(adUnitID: "adUnitID-XXXX")
            interstitial.delegate = self
            interstitial.loadRequest(GADRequest())
            return interstitial
        }
        
        func getAd(){
            if (self.interstitial.isReady)
            {
                self.interstitial.presentFromRootViewController(self)
                self.interstitial = self.createAndLoadInterstitial()
            }
        }
        @IBOutlet weak var ataturkButton: UIButton!
        @IBOutlet weak var sabihaButton: UIButton!
        @IBOutlet weak var esenbogaButton: UIButton!
        @IBOutlet weak var weatherButton: UIButton!
        @IBOutlet weak var statusLabel: UILabel!
        @IBOutlet weak var playButton: UIButton!
        @IBOutlet weak var webViewButton: UIButton!
        var googleBannerView: GADBannerView!
override func viewDidLoad() {
            super.viewDidLoad()
        }
class PlayerAv {
            var audioLink: String?
            var player: AVPlayer
            init(link: String) {
                self.audioLink = link
                self.player = AVPlayer(URL: NSURL(string: link))
            }
        }
        var myPlayer = PlayerAv(link: "http://somewebsite.com/abc.pls")
        var setTowerState = ""
        
        @IBAction func sliderValueChanged(sender: UISlider) {
            var currentValue = Float(sender.value)
            println(currentValue)
            myPlayer.player.volume = currentValue
        }
        @IBAction func getWeatherWindow(sender: AnyObject) {
            UIApplication.sharedApplication().openURL(NSURL(string: "http://somewebpage.com")!)
            println("Directed to weather page")
        }
        @IBAction func changeToAtaturk() {
            myPlayer.player.pause()
            myPlayer = PlayerAv(link: "http://somewebsite.com/abc.pls")
            myPlayer.audioLink == ""
            println("\(myPlayer.audioLink!)--a")
            playButton.setTitle("Pause", forState: UIControlState.Normal)
            myPlayer.player.play()
            setTowerState = "ataturk"
            statusLabel.text = "Status: Playing, LTBA"
        }
        @IBAction func changeToEsenboga() {
            myPlayer.player.pause()
            myPlayer = PlayerAv(link: "http://somewebsite.com/def.pls")
            println("\(myPlayer.audioLink!)--a")
            playButton.setTitle("Pause", forState: UIControlState.Normal)
            myPlayer.player.play()
            setTowerState = "esenboga"
            statusLabel.text = "Status: Playing, LTAC"
        }
        @IBAction func changeToSabiha() {
            myPlayer.player.pause()
            myPlayer = PlayerAv(link: "http://somewebsite.com/efg.pls")
            println("\(myPlayer.audioLink!)--a")
            playButton.setTitle("Pause", forState: UIControlState.Normal)
            myPlayer.player.play()
            setTowerState = "sabiha"
            statusLabel.text = "Status: Playing, LTFJ"
        }
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        @IBAction func playButtonPressed(sender: AnyObject) {
            toggle()
        }
        func toggle() {
            if playButton.titleLabel?.text == "Play" {
                playRadio()
                println("Playing")
                statusLabel.text = "Status: Playing"
            } else {
                pauseRadio()
                println("Paused")
                statusLabel.text = "Status: Paused"
            }
        }
        func playRadio() {
            myPlayer.player.play()
            playButton.setTitle("Pause", forState: UIControlState.Normal)   
        }
        func pauseRadio() {
            myPlayer.player.pause()
            playButton.setTitle("Play", forState: UIControlState.Normal)
        }
    }

Ios Solutions


Solution 1 - Ios

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

Solution 2 - Ios

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

Solution 3 - Ios

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

Solution 4 - Ios

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondo it betterView Question on Stackoverflow
Solution 1 - IosLeo DabusView Answer on Stackoverflow
Solution 2 - IosPratikView Answer on Stackoverflow
Solution 3 - IosM Hamayun zebView Answer on Stackoverflow
Solution 4 - IosPrashant GaikwadView Answer on Stackoverflow