我不确定我是否缺少功能或某些功能,但是当用户电话响起或者他们询问siri或任何阻止我的应用程序音频播放的内容时,我不确定。用户完成任务后,它不会重新开始播放我的应用。
我想知道我是否缺少某个功能,或者Apple iOS应用程序不能做到这一点吗?
我认为这可能与以下原因有关:
func setupRemoteTransportControls() {
// Get the shared MPRemoteCommandCenter
let commandCenter = MPRemoteCommandCenter.shared()
// Add handler for Play Command
commandCenter.playCommand.addTarget { [unowned self] event in
if self.player?.rate == 0.0 {
self.player?.play()
return .success
}
return .commandFailed
}
// Add handler for Pause Command
commandCenter.pauseCommand.addTarget { [unowned self] event in
if self.player?.rate == 1.0 {
self.player?.pause()
return .success
}
return .commandFailed
}
// self.nowplaying(artist: "Anna", song: "test")
}
我发现我需要添加这部分,但是我怎么称呼它呢?
func handleInterruption(notification: Notification) {
guard let userInfo = notification.userInfo,
let interruptionTypeRawValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
let interruptionType = AVAudioSession.InterruptionType(rawValue: interruptionTypeRawValue) else {
return
}
switch interruptionType {
case .began:
print("interruption began")
case .ended:
print("interruption ended")
default:
print("UNKNOWN")
}
}
答案 0 :(得分:2)
您需要将音频会话设置为AVAudioSessionCategoryPlayback
。如果您未设置此模式,则将使用默认模式AVAudioSessionCategorySoloAmbient
。
您可以在didFinishLaunching
中设置模式。
例如
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Get the singleton instance.
let audioSession = AVAudioSession.sharedInstance()
do {
// Set the audio session category, mode, and options.
try audioSession.setCategory(.playback, mode: .default, options: [])
} catch {
print("Failed to set audio session category.")
}
// Other post-launch configuration.
return true
}
您还需要实现interruption observation
func setupNotifications() {
// Get the default notification center instance.
let nc = NotificationCenter.default
nc.addObserver(self,
selector: #selector(handleInterruption),
name: AVAudioSession.interruptionNotification,
object: nil)
}
@objc func handleInterruption(notification: Notification) {
// To be implemented.
}