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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30280519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:59:42  来源:igfitidea点击:

How to Play Audio in Background Swift?

iosswiftaudioavfoundation

提问by do it better

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

视图控制器.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)
        }
    }

回答by Leo Dabus

You need to set your app Capabilities Background Modes (Audio and AirPlay) and set your AVAudioSession category to AVAudioSessionCategoryPlayback and set it active

您需要设置您的应用程序功能后台模式(音频和 AirPlay)并将您的 AVAudioSession 类别设置为 AVAudioSessionCategoryPlayback 并将其设置为活动

From Xcode 11.4 ? Swift 5.2

从 Xcode 11.4 开始?斯威夫特 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

在此处输入图片说明

回答by Pratik

Xcode 10.2.1Swift 4

Xcode 10.2.1斯威夫特 4

Please add the following code in your AppDelegate

请在您的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 optionsas 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

并且不要忘记在后台模式下启用音频和播放 在此处输入图片说明

回答by hamayun zeb

Only paste on the viewDidload

只粘贴到 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()

回答by Prashant Gaikwad

Swift 5 Xcode 11.2.1

斯威夫特 5 Xcode 11.2.1

Add this code where you have initialized the AudioPlayer.

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

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