How to detect AVPlayer actually started to play in swift - ios

Hello I have set my UISliderminimum value to 0.00. Then I set it's max value in this way.
self.viewPlayer.layer.addSublayer(playerLayer)
let duration : CMTime = avPlayer.avPlayer.currentItem!.asset.duration
let seconds : Float64 = CMTimeGetSeconds(duration)
sliderBar.maximumValue=Float(seconds)
sliderBar!.isContinuous = false
sliderBar!.tintColor = UIColor.green
But I am getting this exception
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Attempting to set a slider's minimumValue (0.000000) to be larger than the maximumValue (nan)'
enter code here
I know after prepareForPlay() to actual playing it takes some time to really play the video. So how can I detect when the player really started to play the video?
Please help me.
Thanks

Since iOS 10 you can observe timeControlStatus property of AVPlayer. It can be .playing.
Check the code:
private func setupAVPlayer() {
avPlayer.addObserver(self, forKeyPath: "status", options: [.old, .new], context: nil)
if #available(iOS 10.0, *) {
avPlayer.addObserver(self, forKeyPath: "timeControlStatus", options: [.old, .new], context: nil)
} else {
avPlayer.addObserver(self, forKeyPath: "rate", options: [.old, .new], context: nil)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if object as AnyObject? === avPlayer {
if keyPath == "status" {
if avPlayer.status == .readyToPlay {
avPlayer.play()
}
} else if keyPath == "timeControlStatus" {
if #available(iOS 10.0, *) {
if avPlayer.timeControlStatus == .playing {
videoCell?.muteButton.isHidden = false
} else {
videoCell?.muteButton.isHidden = true
}
}
} else if keyPath == "rate" {
if avPlayer.rate > 0 {
videoCell?.muteButton.isHidden = false
} else {
videoCell?.muteButton.isHidden = true
}
}
}
}

Here is what I did to actually know when video started (not when it's only ready to start).
Swift 4
player = AVPlayer(url: URL(fileURLWithPath: path))
player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "rate" {
if player.rate > 0 {
print("video started")
}
}
}

You can add an observer on the object of your AVPlayer like this
player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
and you can check the status change with your AVPlayer like this
func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutableRawPointer) {
if keyPath == "status" {
print(player.status)
}
}

From Apple's docs:
You can observe an AVPlayerLayer object’s readyForDisplay property to be notified when the layer has user-visible content. In particular, you might insert the player layer into the layer tree only when there is something for the user to look at and then perform a transition from

You could create a Combine publisher and observe the rate property:
let isPlayingPublisher: AnyPublisher<Bool, Never> = NotificationCenter.default
.publisher(for: AVPlayer.rateDidChangeNotification, object: player)
.compactMap({ $0.object as? AVPlayer })
.map(\.rate)
.map({ $0 != 0 })
.eraseToAnyPublisher()
In SwiftUI you could then receive the value:
.onReceive(isPlayingPublisher) { isPlaying in
}

Declare AVPlayer Global
var streamPlayer = AVPlayer()
func playStreamAudio( for audioUrl:String)
{
guard streamPlayer.timeControlStatus != .playing else {
streamPlayer.pause()
return
}
let url = audioUrl //"http://192.168.71.11:7891/rec.wav"
let playerItem = AVPlayerItem(url: URL(string:url)!)
streamPlayer = AVPlayer(playerItem:playerItem)
streamPlayer.rate = 1.0;
streamPlayer.volume = 1.0
streamPlayer.play()
}

SUPER EASY SOLUTION SWIFT 4-5:
Just check the timeControlStatus!: (also works with PlayerQueue)
if avPlayer?.timeControlStatus.rawValue == 2 {
//video is playing (playing)
} else if avPlayer?.timeControlStatus.rawValue == 0 {
//video is not playing (paused)
}
the raw value will give you its current state :)

Another, simpler, approach is something like:
if videoPlayer.rate != 0 && videoPlayer.error == nil {
print("video player is playing.................")
} else {
print("video player is NOT playing.")
}
Where videoPlayer is of type AVPlayer, obviously.

Related

Swift AVAudioPlayer's playing status always be true?

Here's my code:
#objc func playSmusic1() {
guard let url = Bundle.main.url(forResource: "Snote6", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
guard let player = player else { return }
while (true) {
player.play()
player.enableRate = true;
player.rate = playrate
if !player.isPlaying {
break
}
}
} catch let error {
print(error.localizedDescription)
}
}
I found player.isPlaying properties always be true, so sometimes a tone will be play for 2 or 3 times. How to fix this bug? Thanks a lot!
First: Don't use while(true) for checking because it blocks the main thread!
You should add KVO observer to check this property asynchronously e.g.:
class YourController : UIViewController {
var player: AVAudioPlayer?
//...
deinit {
player?.removeObserver(self, forKeyPath: #keyPath(AVAudioPlayer.isPlaying))
}
func play() {
//...
player?.addObserver(self,
forKeyPath: #keyPath(AVAudioPlayer.isPlaying),
options: .new,
context: nil)
player?.play()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(AVAudioPlayer.isPlaying) {
if let isPlaying = player?.isPlaying {
print(isPlaying)
}
}
else {
self.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}

How can I check if my AVPlayer is buffering? for AVPlayer [duplicate]

I want to detect if my AVPlayer is buffering for the current location, so that I can show a loader or something. But I can't seem to find anything in the documentation for AVPlayer.
You can observe the values of your player.currentItem:
playerItem.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .New, context: nil)
playerItem.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .New, context: nil)
playerItem.addObserver(self, forKeyPath: "playbackBufferFull", options: .New, context: nil)
then
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if object is AVPlayerItem {
switch keyPath {
case "playbackBufferEmpty":
// Show loader
case "playbackLikelyToKeepUp":
// Hide loader
case "playbackBufferFull":
// Hide loader
}
}
}
For me above accepted answer didn't worked but this method does.You can use timeControlStatus but it is available only above iOS 10.
According to apple's official documentation
A status that indicates whether playback is currently in progress,
paused indefinitely, or suspended while waiting for appropriate
network conditions
Add this observer to the player.
player.addObserver(self, forKeyPath: “timeControlStatus”, options: [.old, .new], context: nil)
Then,Observe the changes in
func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
method.Use below code inside above method
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "timeControlStatus", let change = change, let newValue = change[NSKeyValueChangeKey.newKey] as? Int, let oldValue = change[NSKeyValueChangeKey.oldKey] as? Int {
let oldStatus = AVPlayer.TimeControlStatus(rawValue: oldValue)
let newStatus = AVPlayer.TimeControlStatus(rawValue: newValue)
if newStatus != oldStatus {
DispatchQueue.main.async {[weak self] in
if newStatus == .playing || newStatus == .paused {
self?.loaderView.isHidden = true
} else {
self?.loaderView.isHidden = false
}
}
}
}
}
This is tested on iOS 11 above with swift 4 and It is working.
The accepted answer didn't work for me, I used the code below to show the loader efficiently.
Swift 3
//properties
var observer:Any!
var player:AVPlayer!
self.observer = self.player.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 600), queue: DispatchQueue.main) {
[weak self] time in
if self?.player.currentItem?.status == AVPlayerItemStatus.readyToPlay {
if let isPlaybackLikelyToKeepUp = self?.player.currentItem?.isPlaybackLikelyToKeepUp {
//do what ever you want with isPlaybackLikelyToKeepUp value, for example, show or hide a activity indicator.
}
}
}
Swift 4 observations:
var playerItem: AVPlayerItem?
var playbackLikelyToKeepUpKeyPathObserver: NSKeyValueObservation?
var playbackBufferEmptyObserver: NSKeyValueObservation?
var playbackBufferFullObserver: NSKeyValueObservation?
private func observeBuffering() {
let playbackBufferEmptyKeyPath = \AVPlayerItem.playbackBufferEmpty
playbackBufferEmptyObserver = playerItem?.observe(playbackBufferEmptyKeyPath, options: [.new]) { [weak self] (_, _) in
// show buffering
}
let playbackLikelyToKeepUpKeyPath = \AVPlayerItem.playbackLikelyToKeepUp
playbackLikelyToKeepUpKeyPathObserver = playerItem?.observe(playbackLikelyToKeepUpKeyPath, options: [.new]) { [weak self] (_, _) in
// hide buffering
}
let playbackBufferFullKeyPath = \AVPlayerItem.playbackBufferFull
playbackBufferFullObserver = playerItem?.observe(playbackBufferFullKeyPath, options: [.new]) { [weak self] (_, _) in
// hide buffering
}
}
Observers need to be removed after we are done observing.
To remove these three observers just set playbackBufferEmptyObserver, playbackLikelyToKeepUpKeyPathObserver and playbackBufferFullObserver to nil.
No need to remove them manually (this is specific for observe<Value>(_ keyPath:, options:, changeHandler:) method.
#Updated in Swift 4 and worked fine
As through i have gone with accepted answer but didn't work in swift 4 for me so after certain research i have found this thinks from apple doc. There are two way to determine AVPlayer states that are,
addPeriodicTimeObserverForInterval:queue:usingBlock: and
addBoundaryTimeObserverForTimes:queue:usingBlock:
and using ways is like this
var observer:Any?
var avplayer : AVPlayer?
func preriodicTimeObsever(){
if let observer = self.observer{
//removing time obse
avplayer?.removeTimeObserver(observer)
observer = nil
}
let intervel : CMTime = CMTimeMake(1, 10)
observer = avplayer?.addPeriodicTimeObserver(forInterval: intervel, queue: DispatchQueue.main) { [weak self] time in
guard let `self` = self else { return }
let sliderValue : Float64 = CMTimeGetSeconds(time)
//this is the slider value update if you are using UISlider.
let playbackLikelyToKeepUp = self.avPlayer?.currentItem?.isPlaybackLikelyToKeepUp
if playbackLikelyToKeepUp == false{
//Here start the activity indicator inorder to show buffering
}else{
//stop the activity indicator
}
}
}
And Don't forget to kill time observer to save from memory leak. method for killing instance, add this method according to your need but i have used it in viewWillDisappear method.
if let observer = self.observer{
self.avPlayer?.removeTimeObserver(observer)
observer = nil
}
Updated for Swift 4.2
var player : AVPlayer? = nil
let videoUrl = URL(string: "https://wolverine.raywenderlich.com/content/ios/tutorials/video_streaming/foxVillage.mp4")
self.player = AVPlayer(url: videoUrl!)
self.player?.addPeriodicTimeObserver(forInterval: CMTimeMake(value: 1, timescale: 600), queue: DispatchQueue.main, using: { time in
if self.player?.currentItem?.status == AVPlayerItem.Status.readyToPlay {
if let isPlaybackLikelyToKeepUp = self.player?.currentItem?.isPlaybackLikelyToKeepUp {
//do what ever you want with isPlaybackLikelyToKeepUp value, for example, show or hide a activity indicator.
//MBProgressHUD.hide(for: self.view, animated: true)
}
}
})
Hmm, the accepted solution didn't work for me and the periodic observer solutions seem heavy handed.
Here's my suggestion, observe timeControlerStatus on AVPlayer.
// Add observer
player.addObserver(self,
forKeyPath: #keyPath(AVPlayer.timeControlStatus),
options: [.new],
context: &playerItemContext)
// At some point you'll need to remove yourself as an observer otherwise
// your app will crash
self.player?.removeObserver(self, forKeyPath: #keyPath(AVPlayer.timeControlStatus))
// handle keypath callback
if keyPath == #keyPath(AVPlayer.timeControlStatus) {
guard let player = self.player else { return }
if let isPlaybackLikelyToKeepUp = player.currentItem?.isPlaybackLikelyToKeepUp,
player.timeControlStatus != .playing && !isPlaybackLikelyToKeepUp {
self.playerControls?.loadingStatusChanged(true)
} else {
self.playerControls?.loadingStatusChanged(false)
}
}
In Swift 5.3
Vars:
private var playerItemBufferEmptyObserver: NSKeyValueObservation?
private var playerItemBufferKeepUpObserver: NSKeyValueObservation?
private var playerItemBufferFullObserver: NSKeyValueObservation?
AddObservers
playerItemBufferEmptyObserver = player.currentItem?.observe(\AVPlayerItem.isPlaybackBufferEmpty, options: [.new]) { [weak self] (_, _) in
guard let self = self else { return }
self.showLoadingIndicator(over: self)
}
playerItemBufferKeepUpObserver = player.currentItem?.observe(\AVPlayerItem.isPlaybackLikelyToKeepUp, options: [.new]) { [weak self] (_, _) in
guard let self = self else { return }
self.dismissLoadingIndicator()
}
playerItemBufferFullObserver = player.currentItem?.observe(\AVPlayerItem.isPlaybackBufferFull, options: [.new]) { [weak self] (_, _) in
guard let self = self else { return }
self.dismissLoadingIndicator()
}
RemoveObservers
playerItemBufferEmptyObserver?.invalidate()
playerItemBufferEmptyObserver = nil
playerItemBufferKeepUpObserver?.invalidate()
playerItemBufferKeepUpObserver = nil
playerItemBufferFullObserver?.invalidate()
playerItemBufferFullObserver = nil
We can directly Observe Playback State using the state observer method once is there any playback state changes it will be notified, it's a really easy way and it's tested with swift 5 and iOS 13.0+
var player: AVPlayer!
player.currentItem!.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .new, context: nil)
func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
contexts: UnsafeMutableRawPointer?) {
if (player.currentItem?.isPlaybackLikelyToKeepUp ?? false) {
// End Buffering
} else {
// Buffering is in progress
}
}
Apple Doc Reference
Solution for Xamarin inspired by Marco's answer
// KVO registrations
private void Initialize()
{
playbackBufferEmptyObserver?.Dispose();
playbackBufferEmptyObserver = (NSObject)playerItem.AddObserver("playbackBufferEmpty",
NSKeyValueObservingOptions.New,
AVPlayerItem_BufferUpdated);
playbackLikelyToKeepUpObserver?.Dispose();
playbackLikelyToKeepUpObserver = (NSObject)playerItem.AddObserver("playbackLikelyToKeepUp",
NSKeyValueObservingOptions.New,
AVPlayerItem_BufferUpdated);
playbackBufferFullObserver?.Dispose();
playbackBufferFullObserver = (NSObject)playerItem.AddObserver("playbackBufferFull",
NSKeyValueObservingOptions.New,
AVPlayerItem_BufferUpdated);
}
private void AVPlayerItem_BufferUpdated(NSObservedChange e)
{
ReportVideoBuffering();
}
private void ReportVideoBuffering()
{
// currentPlayerItem is the current AVPlayerItem of AVPlayer
var isBuffering = !currentPlayerItem.PlaybackLikelyToKeepUp;
// NOTE don't make "buffering" as one of your PlayerState.
// Treat it as a separate property instead. Learned this the hard way.
Buffering?.Invoke(this, new BufferingEventArgs(isBuffering));
}
Please note that
Use a weak reference to self in the callback block to prevent creating a retain cycle.
func playRemote(url: URL) {
showSpinner()
let playerItem = AVPlayerItem(url: url)
avPlayer = AVPlayer(playerItem: playerItem)
avPlayer.rate = 1.0
avPlayer.play()
self.avPlayer.addPeriodicTimeObserver(forInterval: CMTimeMake(value: 1,
timescale: 600), queue: DispatchQueue.main, using: { [weak self] time in
if self?.avPlayer.currentItem?.status == AVPlayerItem.Status.readyToPlay {
if let isPlaybackLikelyToKeepUp = self?.avPlayer.currentItem?.isPlaybackLikelyToKeepUp {
self?.removeSpinner()
}
}
})
}
}
Using Combine you can easily subscribe to the publisher for when an AVPlayerItem is buffering or not like so:
// Subscribe to this and update your `View` appropriately
#Published var isBuffering = false
private var observation: AnyCancellable?
observation = avPlayer?.currentItem?.publisher(for: \.isPlaybackBufferEmpty).sink(receiveValue: { [weak self] isBuffering in
self?.isBuffering = isBuffering
})
Here is a simple method, that works with Swift 5.
This will add the loadingIndicator when your player is stalled
NotificationCenter.default.addObserver(self, selector:
#selector(playerStalled(_:)), name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: self.player?.currentItem)
#objc func playerStalled(_ notification: Notification){
self.loadingIndicator.isHidden = false
self.playPauseButton.isHidden = true
}
This will show loader Indicator when buffer is empty:
if let isPlayBackBufferEmpty = self.player?.currentItem?.isPlaybackBufferEmpty{
if isPlayBackBufferEmpty{
self.loadingIndicator.isHidden = false
self.playPauseButton.isHidden = true
}
}
This will hide the loader when player is ready to play:
if self.playerItem?.status == AVPlayerItem.Status.readyToPlay{
if let isPlaybackLikelyToKeepUp = self.player?.currentItem?.isPlaybackLikelyToKeepUp {
if isPlaybackLikelyToKeepUp{
self.loadingIndicator.isHidden = true
self.playPauseButton.isHidden = false
}
}
}

Observing AVPlayer: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled

Hi I'm trying to observe an AVPlayerItem and an AVPlayer in my UIViewController.
But I got some trouble doing it. I've googled a lot and found lot's of examples but none of these worked for me.
Here is my ViewController:
class VideoAudioViewController: UIViewController {
var audioPlayer: AVPlayer!
var playerItem: AVPlayerItem!
private var audio: Audio
private let ITEM_STATUS_PATH = #keyPath(AVPlayerItem.status)
private let PLAYER_STATUS_PATH = #keyPath(AVPlayer.status)
private let PLAYER_RATE_PATH = #keyPath(AVPlayer.rate)
init(for audio: Audio) {
self.audio = audio
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Play audio
playerItem = AVPlayerItem(url: audio.url)
playerItem.addObserver(self, forKeyPath: ITEM_STATUS_PATH, options: [.old, .new], context: nil)
audioPlayer = AVPlayer(playerItem: playerItem)
audioPlayer!.play()
// audioPlayer!.
var audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
} catch {
print("error")
}
NotificationCenter.default.addObserver(
self, selector: #selector(handleInterruption), name: .AVAudioSessionInterruption, object: audioSession)
audioPlayer.addObserver(self, forKeyPath: PLAYER_STATUS_PATH, options: [.old, .new], context: nil)
audioPlayer.addObserver(self, forKeyPath: PLAYER_RATE_PATH, options: [.old, .new], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?,
change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "status" {
switch (audioPlayer.status) {
case AVPlayerStatus.readyToPlay:
print("player status ready to play")
audioPlayer.play()
break
case AVPlayerStatus.failed:
print("player status failed")
break
default:
break
}
return
} else if keyPath == "rate" {
if audioPlayer.rate != 0 {
playPauseButton.setImage(#imageLiteral(resourceName: "ic_pause_circle_outline_white"), for: .normal)
} else {
playPauseButton.setImage(#imageLiteral(resourceName: "ic_play_circle_outline_white"), for: .normal)
}
} else if keyPath == "status" {
switch (playerItem.status) {
case AVPlayerItemStatus.readyToPlay:
print("player item ready to play")
break
case AVPlayerItemStatus.failed:
print("player item failed")
break
default:
break
}
return
}
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
// MARK: - AVAudioPlayer delegate
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 {
playPauseButton.setImage(#imageLiteral(resourceName: "ic_play_circle_outline_white"), for: .normal)
}
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
audioPlayer?.play()
// }
}
}
}
My problem is this:
Terminati
ng app due to uncaught exception 'NSInternalInconsistencyException', reason: '<TheSimpleClub_Nachhilfe.VideoAudioViewController: 0x7fa6ee2b0c10>: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Key path: rate
Observed object: <AVPlayer: 0x60000021c8c0>
Change: {
kind = 1;
new = 1;
old = 1;
}
Context: 0
x0'
The error occurrs in this line:
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
What can I do to resolve this?

How to set AVQuePlayer to the begining after it finishes playing all in Que

I have an AVQuePlayer that is downloading videos a user posts to firebase and then playing them in order via an AVQuePlayer. Everything works fine until the video que plays all vidoes, in which case, if you try and replay the que, a SIGABRT 1 error occurs. I believe this is due to the fact that it is looking for videos to play but none are present. I have already tried to reset the playerItem array after the que finishes but it has come with no luck. Here is what I have so far.
Loads data from Firebase:
func loadStory() {
DataService.ds.REF_POSTS.observe(.value, with: { (snapshot) in
self.posts = []
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {
if let dict = snap.value as? Dictionary<String, Any> {
let key = snap.key
let post = HotPosts(postID: key, postData: dict)
self.posts.append(post)
let media = post.mediaURL
let ref = Storage.storage().reference(forURL: media)
ref.downloadURL(completion: { (url, error) in
if error != nil {
print(error!)
} else {
self.videos.append(url!)
}
})
}
}
}
})
}
Downloads the urls:
func playStory() {
for vid in videos{
asset = AVAsset(url: vid)
let assetKeys = ["playable", "hasProtectedContent"]
let item = AVPlayerItem(asset: asset, automaticallyLoadedAssetKeys: assetKeys)
item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: &myContext)
self.playerItem.append(item)
}
player = AVQueuePlayer(items: playerItem)
print(playerItem.count)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
}
Handles buffering and plays video when ready:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("playing1")
guard context == &myContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
print("playing2")
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItemStatus
print("playing3")
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItemStatus(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
switch status {
case .readyToPlay:
print("We ARE IN THE CLEAR BOIIIIII")
player.play()
break
case .failed:
print("ITem Fialed")
break
case .unknown:
print("Could Not play the video")
break
}
}
}
Try subscribing to this notification and see if it works correctly for your situation:
NotificationCenter.default.addObserver(self, selector: #selector(endOfAudio), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
I also found this in a piece of Apple code, which illustrates the use of some KVO on avQueuePlayer ( https://developer.apple.com/library/content/samplecode/avloopplayer/Listings/Projects_VideoLooper_VideoLooper_QueuePlayerLooper_swift.html )
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
An object that uses AVQueuePlayer to loop a video.
*/
// MARK: Convenience
private func startObserving() {
guard let player = player, !isObserving else { return }
player.addObserver(self, forKeyPath: ObserverContexts.playerStatusKey, options: .new, context: &ObserverContexts.playerStatus)
player.addObserver(self, forKeyPath: ObserverContexts.currentItemKey, options: .old, context: &ObserverContexts.currentItem)
player.addObserver(self, forKeyPath: ObserverContexts.currentItemStatusKey, options: .new, context: &ObserverContexts.currentItemStatus)
isObserving = true
}
private func stopObserving() {
guard let player = player, isObserving else { return }
player.removeObserver(self, forKeyPath: ObserverContexts.playerStatusKey, context: &ObserverContexts.playerStatus)
player.removeObserver(self, forKeyPath: ObserverContexts.currentItemKey, context: &ObserverContexts.currentItem)
player.removeObserver(self, forKeyPath: ObserverContexts.currentItemStatusKey, context: &ObserverContexts.currentItemStatus)
isObserving = false
}
// MARK: KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &ObserverContexts.playerStatus {
guard let newPlayerStatus = change?[.newKey] as? AVPlayerStatus else { return }
if newPlayerStatus == AVPlayerStatus.failed {
print("End looping since player has failed with error: \(player?.error)")
stop()
}
}
else if context == &ObserverContexts.currentItem {
guard let player = player else { return }
if player.items().isEmpty {
print("Play queue emptied out due to bad player item. End looping")
stop()
}
else {
// If `loopCount` has been set, check if looping needs to stop.
if numberOfTimesToPlay > 0 {
numberOfTimesPlayed = numberOfTimesPlayed + 1
if numberOfTimesPlayed >= numberOfTimesToPlay {
print("Looped \(numberOfTimesToPlay) times. Stopping.");
stop()
}
}
/*
Append the previous current item to the player's queue. An initial
change from a nil currentItem yields NSNull here. Check to make
sure the class is AVPlayerItem before appending it to the end
of the queue.
*/
if let itemRemoved = change?[.oldKey] as? AVPlayerItem {
itemRemoved.seek(to: kCMTimeZero)
stopObserving()
player.insert(itemRemoved, after: nil)
startObserving()
}
}
}
else if context == &ObserverContexts.currentItemStatus {
guard let newPlayerItemStatus = change?[.newKey] as? AVPlayerItemStatus else { return }
if newPlayerItemStatus == .failed {
print("End looping since player item has failed with error: \(player?.currentItem?.error)")
stop()
}
}
else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
The problem with AVQueuePlayer is that it removes the AVPlayerItems that have finished playing. An option might be to create a copy of your AVQueuePlayer when your QueuePlayer is completely done playing, then you can just play your copy and make a new copy to play again once that one also finishes.
You could also maintain all your AVPlayerItems in an array and load up a new AVQueuePlayer whenever it's needed.
There is a project on github that might also be helpful, which extends AVQueuePlayer and maintains previous playerItems that have been played on your Queue Player. It can be found through: https://github.com/dgiovann/AVQueuePlayerPrevious

check valid url to play in avplayercontroller?

I have three urls and have to check if these urls have a video link to play or not. I have to esc link if it does not contain video in url and play video from next url. This following code will help to track the playing state.
let playerAV = AVPlayerViewController()
var player = AVPlayer()
playerAV.player = player
playerAV.view.frame = CGRectMake(0, 0, self.videoView.frame.width, self.videoView.frame.height)
self.addChildViewController(playerAV)
self.videoView.addSubview(playerAV.view)
playerAV.didMoveToParentViewController(self)
playerAV.player?.play()
addObserverOfMoviePlayer()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ChannelDetailViewController.notificationObserver(_:)), name:AVPlayerItemDidPlayToEndTimeNotification , object: player.currentItem)
_ = UIDevice.beginGeneratingDeviceOrientationNotifications
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ChannelDetailViewController.deviceOrientationDidChange(_:)) , name:
UIDeviceOrientationDidChangeNotification, object: nil)
playerAV.player!.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.New, context: nil)
playerAV.player!.currentItem!.addObserver(self, forKeyPath: "playbackBufferEmpty", options: NSKeyValueObservingOptions.New, context: nil)
playerAV.player!.currentItem!.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: NSKeyValueObservingOptions.New, context: nil)
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "rate" {
if let rate = change?[NSKeyValueChangeNewKey] as? Float {
if playerAV.player!.currentItem!.status == AVPlayerItemStatus.ReadyToPlay{
if rate != 0 && playerAV.player!.error == nil {
print("normal playback")
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ChannelDetailViewController.somAction), userInfo: nil, repeats: true)
}
else{
timer?.invalidate()
print("movie player stopped")
}
}else if playerAV.player!.currentItem?.status == AVPlayerItemStatus.Unknown{
timer?.invalidate()
print("not ready to play")
}
}
}
if keyPath == "playbackBufferEmpty"{
if playerAV.player?.currentItem?.playbackBufferEmpty == true{
timer?.invalidate()
print("movie player stopped due to no buffer")
}
}
if keyPath == "playbackLikelyToKeepUp" {
if playerAV.player?.currentItem?.playbackLikelyToKeepUp == true{
print("movie player playing after enough data in buffer")
playerAV.player?.play()
}
}
}
Just check the length of the video if it's invalid the length will return as zero with this code :
let assets = AVAsset(URL: NSURL(fileURLWithPath: filePath))
let length=Float(assets.duration.value)/Float(assets.duration.timescale)
if length != 0.0 {
// play it
}
If you have still problem you can ask me anytime.
As of iOS 15 you can use the isPlayable property on AVAsset. Like this:
let asset = AVAsset(URL: NSURL(fileURLWithPath: filePath))
guard asset.isPlayable else {
return
}

Resources