【发布时间】:2015-12-09 11:26:51
【问题描述】:
我正在学习 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")
}
}
【问题讨论】:
-
方法是否被正确调用?尤其是 resumeNow 方法。
-
是的 - 我在通话终止 3 秒后看到日志显示“尝试重新启动”。
标签: ios swift audio avfoundation avplayer