首页 > 解决方案 > 通话后恢复 AVPlayer

问题描述

似乎有很多解决方案可以解决这个问题,但这些解决方案都没有对我有用。我目前正在使用 Swift 5。我有一个 AVPlayer 在我的 ViewController 中播放动画(循环)。当通过CallKit来电时,无论我是接听还是拒接,处理完来电后AVPlayer播放的动画都不会恢复。中断处理程序似乎在中断之前被调用,但通常不会在中断之后被调用。

        override func viewDidLoad() {
            super.viewDidLoad()
            prepareBGVideo()
            ...
            NotificationCenter.default.addObserver(
                self,
                selector: #selector(applicationWillEnterForeground(notification:)),
                name: UIApplication.willEnterForegroundNotification,
                object: nil)
            ...
        }        

       func prepareBGVideo() {
            guard let path = Bundle.main.path(forResource: "animation", ofType:"mp4") else {
                print("video not found")
                return
            }

            let item = AVPlayerItem(url: URL(fileURLWithPath: path))
            avPlayer = AVPlayer(playerItem: item)

            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(loopVideoBG),
                                                   name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                                   object: item)
            NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption(notification:)), name: AVAudioSession.interruptionNotification, object: nil)
            avPlayerLayer = AVPlayerLayer(player: avPlayer)
            avPlayerLayer.backgroundColor = UIColor.black.cgColor
            avPlayer.volume = 0
            avPlayer.actionAtItemEnd = .none
            avPlayer.play()

            view.backgroundColor = .clear
            avPlayerLayer.frame = view.layer.bounds
            view.layer.insertSublayer(avPlayerLayer, at: 0)
            avPlayerLayer.videoGravity = isIPAD ? AVLayerVideoGravity.resize : AVLayerVideoGravity.resizeAspectFill // Changed from AVLayerVideoGravity.resizeAspect to AVLayerVideoGravity.resize so that video fits iPad screen

            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(willEnterForeground),
                                                   name: UIApplication.willEnterForegroundNotification,
                                                   object: nil)
        }

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

        /// Resume video while app wake up from background
        @objc func willEnterForeground() {
            avPlayer.seek(to: CMTime.zero)
            JPUtility.shared.performOperation(0.1) {
                self.avPlayer.play()
            }
        }

        @objc func loopVideoBG() {
            avPlayer.seek(to: CMTime.zero)
            avPlayer.play()
        }

以下是我尝试过的所有解决方案:

  1. 等待两秒钟后self.avPlayer.play()拨入if options.contains(.shouldResume){}
  2. 中断开始时设置AVAudioSession.sharedInstance().setActive为假,中断结束时设置为真。这种方法的问题是该if interruption == .ended {}块并不总是被调用,因此设置setActive无效。
  3. AVAudioSession播放类别设置为AVAudioSessionCategoryOptions.MixWithOthers。我的动画无论如何都没有音频。

我已经看到提到恢复播放,applicationDidBecomeActive(_:)但有些人建议不要这样做。这会被认为是好的做法吗?

有没有办法确保else if type == .ended {}块被执行?或者也许比观察更可靠的解决方法AVAudioSession.interruptionNotification

标签: iosavfoundationavplayerswift5avaudiosession

解决方案


我解决了这个问题,但创建了一个共享VideoPlayer类,其中包含对所有具有动画的屏幕的引用。

import Foundation
import UIKit
import AVKit

    class VideoPlayer: NSObject {

        static var shared: VideoPlayer = VideoPlayer()

        var avPlayer: AVPlayer!
        var avPlayerLayer: AVPlayerLayer!

        weak var vcForConnect:ConnectVC?
        weak var vcForList:ListVC?

        override init() {
            super.init()
            guard let path = Bundle.main.path(forResource: "animation", ofType:"mp4") else {
                print("video not found")
                return
            }
            avPlayer = AVPlayer(url: URL(fileURLWithPath: path))
            avPlayerLayer = AVPlayerLayer(player: avPlayer)
            avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
            avPlayer.volume = 0
            avPlayer.actionAtItemEnd = .none
            loopVideo(videoPlayer: avPlayer)
            avPlayer.play()
            NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption(notification:)), name: AVAudioSession.interruptionNotification, object: nil)

        }

        deinit {
            avPlayer.pause()
        }

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

        func resumeAllAnimations() {
            self.avPlayer.play()
            if vcForList?.avPlayer != nil {
                vcForList?.avPlayer.play()
            }
            if vcForConnect?.avPlayer != nil {
                vcForConnect?.avPlayer.play()
            }
            if vcForConnect?.avPlayerBG != nil {
                vcForConnect?.avPlayerBG.play()
            }
        }
        ...
    }

然后我通过调用resumeAllAnimations()来恢复动画applicationDidBecomeActive(_:)AppDelegate.swift如下所示:

func applicationDidBecomeActive(_ application: UIApplication) {
        VideoPlayer.shared.resumeAllAnimations()
        ...
}

推荐阅读