如何在后台Swift中播放音频?

时间:2015-05-16 20:39:15

标签: ios swift audio avfoundation

如你所见,我正在播放音频广播。但是,当我按下主页按钮退出应用程序流停止或我听不到。如何在后台继续流式传输并从锁定屏幕中进行监听?

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

4 个答案:

答案 0 :(得分:132)

您需要设置应用功能背景模式(音频和AirPlay)并将AVAudioSession类别设置为AVAudioSessionCategoryPlayback并将其设置为活动

来自Xcode 8.2.1•Swift 3.0.2以后

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

答案 1 :(得分:1)

仅粘贴到viewDidload

enter image description here

InstrumentUserControl

答案 2 :(得分:1)

Swift 5 Xcode 11.2.1

在初始化AudioPlayer的位置添加此代码。

audioPlayer.delegate = self
audioPlayer.prepareToPlay()
let audioSession = AVAudioSession.sharedInstance()
do{
    try audioSession.setCategory(AVAudioSession.Category.playback)
}
catch{
    fatalError("playback failed")
}

答案 3 :(得分:0)

Xcode 10.2.1 Swift 4

请在您的 AppDelegate

中添加以下代码
 options: [.allowAirPlay, .defaultToSpeaker]

注意:-请根据需要配置选项。例如在播放视频文件时停止添加背景音频

rdd

并且不要忘记在“后台”模式下启用音频和播放 enter image description here