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

前端之家收集整理的这篇文章主要介绍了ios – 如何在Swift 2 / AVPlayer中恢复背景音频?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在学习 Swift作为我的第一门编程语言. @H_301_2@中断后我已经挣了好几个小时才恢复背景音频播放(例如通话)

@H_301_2@应该怎么做:

@H_301_2@>当应用程序转到后台时,音频会继续播放(工作)
>当被呼叫中断时,开始通知中断
(作品)
>通话结束后,获取中断通知
结束(工作)
>继续播放音频(不起作用 – 什么都听不到)

@H_301_2@真的很感激任何帮助!谢谢

@H_301_2@笔记:

@H_301_2@>该应用程序已注册为背景音频,并在中断前播放正常
>我已经尝试过,没有时间延迟恢复播放 – 都没有工作

@H_301_2@码:

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

解决方法

终于明白了! @H_301_2@解决方案:通过将setCategory行更改为:添加了mixable选项:

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

猜你在找的iOS相关文章