如何在Swift 2 / AVPlayer中恢复背景音频?

我正在学习Swift作为我的第一个编程语言。

我已经挣扎了好几个小时,以便在中断后恢复后台音频播放 (例如呼叫)

应该发生什么:

  • 音频继续播放时,应用程序去背景(作品)
  • 当被打电话中断时,开始中断通知(工作)
  • 当通话结束时,获取中断结束通知(工作)
  • 继续播放音频( 不工作 - 听不到任何声音
  • 真的很感谢任何帮助! 谢谢

    笔记:

  • 该应用程序已注册后台音频并在中断之前播放正常
  • 我曾尝试过,没有时间延迟来继续比赛 - 都没有成功
  • 码:

    import UIKit
    import AVFoundation
    
    var player: AVQueuePlayer!
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            do {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                try AVAudioSession.sharedInstance().setActive(true, withOptions: .NotifyOthersOnDeactivation)
            } catch { }
            let songNames = ["music"]
            let songs = songNames.map { AVPlayerItem(URL:
                NSBundle.mainBundle().URLForResource($0, withExtension: "mp3")!) }
            player = AVQueuePlayer(items: songs)
    
            let theSession = AVAudioSession.sharedInstance()
            NSNotificationCenter.defaultCenter().addObserver(self,
                selector:"playInterrupt:",
                name:AVAudioSessionInterruptionNotification,
                object: theSession)
    
            player.play()
        }
    
        func playInterrupt(notification: NSNotification) {
    
            if notification.name == AVAudioSessionInterruptionNotification
                && notification.userInfo != nil {
    
                var info = notification.userInfo!
                var intValue: UInt = 0
                (info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)
                if let type = AVAudioSessionInterruptionType(rawValue: intValue) {
                    switch type {
                    case .Began:
                        print("aaaaarrrrgggg you stole me")
                        player.pause()
    
                    case .Ended:
                        let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
                    }
                }
            }
        }
        func resumeNow(timer : NSTimer) {
            player.play()
            print("attempted restart")
        }
    }
    

    终于明白了!

    解决方案:通过将setCategory行更改为以下内容添加可混合选项:

    AVAudioSession.sharedInstance()。setCategory(AVAudioSessionCategoryPlayback,withOptions:AVAudioSessionCategoryOptions.MixWithOthers)


    我写了这样的代码,并成功地恢复了通话结束后的音频。 我建立在Xcode 6.4上,并在我的iPhone 4S上运行该应用程序。

    var player: AVQueuePlayer! = nil
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func viewDidAppear(animated: Bool)
    {
        super.viewDidAppear(true)
    
        var song = AVPlayerItem(URL: NSBundle.mainBundle().URLForResource("AlmostAYearAgo", withExtension: "mp3")!)
        player = AVQueuePlayer(items: [song])
    
        let theSession = AVAudioSession.sharedInstance()
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "playInterrupt:", name: AVAudioSessionInterruptionNotification, object: theSession)
    
        player.play()
    }
    
    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func playInterrupt(notification: NSNotification)
    {
        if notification.name == AVAudioSessionInterruptionNotification && notification.userInfo != nil
        {
            var info = notification.userInfo!
            var intValue: UInt = 0
    
            (info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)
    
            if let type = AVAudioSessionInterruptionType(rawValue: intValue)
            {
                switch type
                {
                case .Began:
                    print("aaaaarrrrgggg you stole me")
                    player.pause()
                case .Ended:
                    let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
                }
            }
        }
    }
    
    func resumeNow(timer : NSTimer)
    {
        player.play()
        print("attempted restart")
    }
    

    对于我结束中断后重新加载播放器解决问题:

        func interruptionNotification(_ notification: Notification) {
        guard let type = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
          let interruption = AVAudioSessionInterruptionType(rawValue: type) else {
            return
        }
        if interruption == .ended && playerWasPlayingBeforeInterruption {
          player.replaceCurrentItem(with: AVPlayerItem(url: radioStation.url))
          play()
        }
      }
    
    链接地址: http://www.djcxy.com/p/87861.html

    上一篇: How to resume background audio in Swift 2 / AVPlayer?

    下一篇: Determine OS newline in JavaScript