Skip to content

ZonPlayer is a player library base on AVPlayer with cache and remote control support on iOS.

License

Notifications You must be signed in to change notification settings

ZeroOnet/ZonPlayer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

50 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ZonPlayer

ZonPlayer is a player library base on AVPlayer with cache and remote control support in iOS. For convenience, we defined interfaces can be called by chain.

Features

  • Configure AVAudioSession asynchronously to prevent the main thread from hang.
  • Support 3rd-party cache like VIMediaCache. There are presetted with ZPC.Harvest and ZPC.Streaming(base on AVAssetResourceLoader).
  • Manage now playing info and remote control command.
  • Use plugin to intercept progress for streaming playback.
  • Retry automatically if then player has an error, eg: media services were reset.

Usage

    let player: ZonPlayable = ZonPlayer.player(URLConvertible)
        .session(ZonPlayer.Sessionable)
        .cache(ZonPlayer.Cacheable) // Conform ZonPlayer.Cacheable to customize cache category.
        .remoteControl(self) { wlf, payload in // Conform ZonPlayer.RemoteControllable to customize background playback controller.
            payload.title(String).artist(String)....
        }
        .onPaused(self) { wlf, payload in // Conform ZonPlayer.Observable to listen player.
        }
        .activate(in: ZonPlayerView)

    // Conform ZonPlayer.Controllable to control player instance.
    player.pause()
    player.play()
    player.seek(to: 0)
    // ...

    // Conform ZonPlayer.Gettable to read player status.
    player.currentTime
    player.duration
    player.url
    // ...

Integrate 3rd-party cache:

import VIMediaCache

final class TestCache: ZonPlayer.Cacheable {
    let manager = VIResourceLoaderManager()

    func prepare(url: URL, completion: @escaping (Result<AVURLAsset, ZonPlayer.Error>) -> Void) {
        let item = manager.playerItem(with: url).unsafelyUnwrapped
        let asset = (item.asset as? AVURLAsset).unsafelyUnwrapped
        completion(.success(asset))
    }
}

func play() {
    let player = ZonPlayer.player(url).cache(TestCache())
}

Notice: before using ZPC.Streaming, it is advisable to ensure that the URL supports random access to avoid potential unexpected issues. Below is the official documentation explanation for isByteRangeAccessSupported:

If this property is not true for resources that must be loaded incrementally, loading of the resource may fail. Such resources include anything that contains media data.

Compatibility

In iOS 18.0.1, we encountered an issue where video playback sometimes has no sound, occasionally accompanied by video stuttering. The example code is as follows:

func seekAndPause(to time: TimeInterval) {
    _player?.seek(to: time) { [weak self] _ in
        self?._player.pause()
    }
}

let time: TimeInterval = 10 // Any time
seekAndPause(to: time)
seekAndPause(to: time) // Call repeatedly

The official documentation describes the completionHandler parameter for AVPlayer().seek is:

The completion handler for any prior seek request that is still in process will be invoked immediately with the finished parameter set to false. If the new request completes without being interrupted by another seek request or by any other operation the specified completion handler will be invoked with the finished parameter set to true.

Eventually, we discovered that when the completionHandler invocation flag is set to false, playback control encounters this issue. Thus, the fix is quite simple:

func seekAndPause(to time: TimeInterval) {
    _player?.seek(to: time) { [weak self] in
        guard $0 else { return }
        self?._player.pause()
    }
}

Issues? Features!

AVPlayer Unexpectedly Pauses After View Controller is Popped

Scenario:

  • A UIViewController (Controller A) hosts an AVPlayer for video playback.
  • Background audio playback is enabled via AVAudioSession.
  • The app enters background → then returns to foreground.
  • Immediately after returning to foreground, Controller A is popped from the navigation stack.
  • The controller instance is retained manually and not deallocated.
  • ❗️ Unexpected behavior: AVPlayer pauses automatically after pop, even though play() was not interrupted and no errors were triggered.

Possible Cause: When Controller A is popped, its view is removed from the view hierarchy. If the AVPlayerLayer is attached to self.view.layer, it may lose its rendering context. This could cause AVPlayer to automatically pause, especially after returning from background, because the rendering engine may detect that there is no active video layer available.

Fix Example:

final class A: UIViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        video.playerView.playerLayer.player = _stashedPlayer
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        let playerLayer = video.playerView.playerLayer
        _stashedPlayer = playerLayer?.player
        playerLayer?.player = nil
    }
}

Requirements

  • iOS 13.0 or later
  • Swift 6.0 or later

Installation

CocoaPods

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '13.0'
use_frameworks!

target 'MyApp' do
  pod 'ZonPlayer', '~> 1.1.0'
end

Carthage

github "ZeroOnet/ZonPlayer" ~> 1.0.0

Swift Package Manager

  • File > Swift Packages > Add Package Dependency
  • Add git@github.com:ZeroOnet/ZonPlayer.git
  • Select "Up to Next Major" with "1.0.0"

Author

ZeroOnet, zeroonetworkspace@gmail.com

Blogs

从头撸一个播放器 I —— ZonPlayer 需求分析及接口设计
从头撸一个播放器 II —— 音频会话、远程控制和播放器实现
从头撸一个播放器 III —— 缓存
从头撸一个播放器 IV(终) —— Github Action 与组件发布

Reference

Alamofire
Kingfisher
VIMediaCache

License

ZonPlayer is available under the MIT license. See the LICENSE file for more info.

About

ZonPlayer is a player library base on AVPlayer with cache and remote control support on iOS.

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published