web-dev-qa-db-fra.com

Comment lire de l'audio en arrière-plan Swift?

Comme vous le voyez, je diffuse une émission audio. Mais lorsque j'appuie sur le bouton d'accueil et que je quitte l'application, le streaming s'arrête ou je n'entends pas. Comment puis-je continuer à diffuser en arrière-plan et l'écouter à partir de l'écran de verrouillage?

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: "ca-app-pub-5378899862041789/2782958552")
            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://www.liveatc.net/play/ltba.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://www.aviationweather.gov/adds/metars/?station_ids=ltac&std_trans=standard&chk_metars=on&hoursStr=most+recent+only&chk_tafs=on&submitmet=Submit")!)
            println("Directed to weather page")
        }
        @IBAction func changeToAtaturk() {
            myPlayer.player.pause()
            myPlayer = PlayerAv(link: "http://www.liveatc.net/play/ltba.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://www.liveatc.net/play/ltac.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://www.liveatc.net/play/ltfj.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)
        }
    }
45
do it better

Vous devez définir les modes d'arrière-plan des capacités de votre application (Audio et AirPlay) et définir votre catégorie AVAudioSession sur AVAudioSessionCategoryPlayback et l'activer.

à partir de Xcode 8.2.1 • Swift 3.0.2 et versions ultérieures

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
    print("Playback OK")
    try AVAudioSession.sharedInstance().setActive(true)
    print("Session is Active")
} catch {
    print(error)
}

enter image description here

Xcode 10 • Swift 4.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)
}
140
Leo Dabus

Xcode 10.2.1 Swift 4

Veuillez ajouter le code suivant dans votre 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
    }

Remarque: - Veuillez configurer options comme requis. Par exemple, pour arrêter un arrière-plan audio pendant la lecture d'un fichier vidéo, ajoutez

 options: [.allowAirPlay, .defaultToSpeaker]

Et n'oubliez pas d'activer l'audio et la diffusion en mode Arrière-plan enter image description here

2
Pratik

Coller uniquement sur la vue

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()
0
hamayun zeb