ios - 使用 SwiftUI 中断后恢复 AVPlayer

标签 ios swift iphone cocoa-touch swiftui

我正在使用 AVPlayerAVPlayerItem 构建一个广播流应用程序。我构建了我的应用程序来继续在后台播放广播,如下所示:

do {
    try AVAudioSession.sharedInstance().setCategory(.playback)
    try AVAudioSession.sharedInstance().setActive(true)
} catch {
   print(error)
}

AVPlayer 中断后(例如,当用户接到电话时),AVPlayer 不会恢复播放。我需要再次主动播放它才能收听流媒体。

如何使用SwiftUI使AVPlayer在中断后自动恢复? (我找到了一些解决方案,但没有一个适合使用 SwiftUI。

谢谢!

最佳答案

没有任何与 SwiftUI 或一般 UI 相关的内容可以在中断后重新启动播放。

正如苹果documentation中所说:

首先注册到中断通知:

func registerForNotifications() {
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(handleInterruption),
                                           name: .AVAudioSessionInterruption,
                                           object: AVAudioSession.sharedInstance())
}

然后像这样处理通知:

func handleInterruption(_ notification: Notification) {
    guard let info = notification.userInfo,
        let typeValue = info[AVAudioSessionInterruptionTypeKey] as? UInt,
        let type = AVAudioSessionInterruptionType(rawValue: typeValue) else {
            return
    }
    if type == .began {
        // Interruption began, take appropriate actions (save state, update user interface)
    }
    else if type == .ended {
        guard let optionsValue =
            userInfo[AVAudioSessionInterruptionOptionKey] as? UInt else {
                return
        }
        let options = AVAudioSessionInterruptionOptions(rawValue: optionsValue)
        if options.contains(.shouldResume) {
            // Interruption Ended - playback should resume
        }
    }
}

如果这没有帮助,您可以使用其他不适用于您的案例的解决方案来更好地解释您遇到的问题。

关于ios - 使用 SwiftUI 中断后恢复 AVPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61447340/

相关文章:

ios - 从另一个 NSDictionary 中提取一个 NSDictionary

用户取消后,iOS Safari 不识别 url 方案

ios - 如何在 iOS 6 的不同 View 中加载 Web View

ios - Swift - 布局 - 拉伸(stretch) UILabel

ios - 在两个 Storyboard之间切换

swift - 以自定义大小阅读图库视频

ios - 无法通过 UIView 通过 swift 创建 pdf?

ios - CALayer 位置包含 NaN : [nan -__]

ios - 在 iPhone 上播放歌曲时通过麦克风检测噪音

ios - 同一 App ID 下的 iPhone 和 iPad 版本