Skip to content

Instantly share code, notes, and snippets.

@liuzhida33
Created July 8, 2020 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuzhida33/0118d70bf2769d3e4d146295a14ff53a to your computer and use it in GitHub Desktop.
Save liuzhida33/0118d70bf2769d3e4d146295a14ff53a to your computer and use it in GitHub Desktop.
AVPlayer Background Design

AVPlayer Background Design

  1. 使用NSNotification来监听进入后台和前台事件

    .UIApplicationWillEnterForeground .UIApplicationDidEnterBackground

  2. 长按home键不会响应 1. 中的两个通知事件,需要同时使用以下通知

    .UIApplicationWillResignActive .UIApplicationDidBecomeActive

如果AVPlayer的当前项在设备的显示屏上显示视频,则AVPlayer当应用程序发送到后台时,的播放会自动暂停。有两种方法可以防止这种暂停:

  • 禁用播放器项中的视频轨道(仅基于文件的内容)。参见清单1。
  • AVPlayerLayer从与其关联的中删除AVPlayer(将AVPlayerLayer player属性设置为nil)。参见清单2。

Listing 1 Disabling the video tracks in the player item.

import AVFoundation
 
let playerItem = <#Your player item#>
 
let tracks = playerItem.tracks
for playerItemTrack in tracks {
 
    // Find the video tracks.
    if playerItemTrack.assetTrack.hasMediaCharacteristic(AVMediaCharacteristicVisual) {
 
        // Disable the track.
        playerItemTrack.isEnabled = false
    }
}

Listing 2 Remove/Restore the AVPlayerLayer and its associated AVPlayer.

import UIKit
import AVFoundation
 
...
 
// A `UIView` subclass that is backed by an `AVPlayerLayer` layer.
class PlayerView: UIView {
    var player: AVPlayer? {
        get {
            return playerLayer.player
        }
 
        set {
            playerLayer.player = newValue
        }
    }
 
    var playerLayer: AVPlayerLayer {
        return layer as! AVPlayerLayer
    }
 
    override class var layerClass: AnyClass {
        return AVPlayerLayer.self
    }
}
 
...
 
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
 
    var window: UIWindow?
 
    @IBOutlet weak var playerView: PlayerView!
 
    /*
     Remove the AVPlayerLayer from its associated AVPlayer
     once the app is in the background.
     */
    func applicationDidEnterBackground(_ application: UIApplication) {
 
        // Remove the player.
        playerView.player = nil
    }
 
    // Restore the AVPlayer when the app is active again.
    func applicationDidBecomeActive(_ application: UIApplication) {
 
        // Restore the player.
        playerView.player = <#Your player#>
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment