Basic Playback
Create the player
You can create a player instance by supplying a content URL or an
AVURLAsset. Use AVURLAsset for playing protected content so you can
configure license fetching for the asset.
// Create player
if let contentURL = URL(string: playbackAsset.contentUrl) {
let avURLAsset = AVURLAsset(url: contentURL)
let player = FLPlayerFactory.player(asset: avURLAsset)
// Add player's playback view to your controller
// player.playbackView
}
Attach listeners
You can listen to events such as changes in player state, buffering state, seek state, and playback errors by registering a listener or delegate.
extension YourViewController: PlayerDelegate {
func playerStateDidChange(state: PlayerState) {
print("PlayerDelegate: State Change: \(state)")
}
func playerBufferStateDidChange(isBuffering: Bool) {
print("PlayerDelegate: isBuffering: \(isBuffering)")
}
func playerSeekStateDidChange(isSeeking: Bool) {
print("PlayerDelegate: isSeeking: \(isSeeking)")
}
func playerDidFail(with error: FLError) {
print("PlayerDelegate: Player failed with error - \(error)")
}
}
player.delegate = self;
Attach player to a view
You can use the player library with custom player controls or with
AVPlayerViewController from AVKit.
// Custom controls
// Attach the player's playback view to your view controller
// Your view controller can have custom player controls
// based on your UX design requirements
if let playbackView = player.playbackView {
// Set the frame of playback view to your view controller view's bounds
playbackView.frame = yourViewController.view.bounds
yourViewController.view.insertSubview(playbackView, at: 0)
}
To use the player library with AVPlayerViewController, access the underlying
AVPlayer instance through the player's rawPlayer property.
AVPlayerViewController requires this AVPlayer instance to work.
// Use Player with AVPlayerViewController
let avPlayerViewController = AVPlayerViewController()
// Access AVPlayer through rawPlayer property on Player and set it on AVPlayerViewController
if let avplayer = player.rawPlayer as? AVPlayer {
avPlayerViewController.player = avplayer
}
Start playback
The player library provides load, play, pause, and seek APIs. The
play API loads the content if it's not already loaded and starts playback.
player.play()
When you stop or abort playback, the player pauses if it's playing, releases all resources, and returns to idle state.
Note: Always use the control APIs exposed by the FLPlayer library instead of using the raw player APIs directly.
Stop and abort
Use the following methods to stop or abort playback:
- stop() stops rendering and releases all underlying resources.
- abort(with error: FLError) has the same effect as stop(). Additionally, it invokes the playerDidFail(with error: FLError) delegate callback.
Note: Use abort(error: Error) when another component (without user intervention) aborts playback due to policy restrictions and you need to show the appropriate error on the UI.