How to resume background audio in Swift 2 / AVPlayer?
Finally got it!
Solution: added the mixable option by changing the setCategory line to be:
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,
withOptions: .mixWithOthers )
I wrote a code like this and successfully resumed the audio from the phone call ended. I was build on Xcode 6.4 and ran the app on my 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")
}