В течение многих часов я пытался возобновить фоновое воспроизведение звука после прерывания ( например, позвонить)
Что должно произойти:
- Аудио продолжает воспроизводиться, когда приложение переходит в фоновый режим (работает)
- При прерывании звонком получить уведомление о начале прерывания
(работает) - Когда вызов завершится, получите уведомление о прерывании
заканчивается (работает) - Возобновите воспроизведение звука (НЕ работает — ничего не слышно)
Примечания:
- Приложение зарегистрирован для фонового звука и воспроизводится нормально до прерывания
- Я пробовал возобновить воспроизведение с задержкой по времени и без нее — ничего не помогло
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")
}
}
Подробнее здесь: https://stackoverflow.com/questions/325 ... 2-avplayer
Мобильная версия