Swift AVPlayerItem close when finished - ios

I'm extremely new to Swift and iOS development, so please forgive my ignorance.
I'm trying to have the AVPlayer close automatically when the video is done playing. I've thought to attach the "playerDidFinishPlaying" listener to receive the notification, but once I have it, I can't find the method/event to close the Controller. I'm looking to mimic the action of clicking the "Done" button.
Here is a small snippet of code. Hopefully this is enough information. If not, I can provide further info
let destination = segue.destinationViewController as! AVPlayerViewController
let url = NSURL(string: "video url")
destination.player = AVPlayer(URL: url!)
destination.player?.play()
I've added the following notification, but again, I'm not sure what to do with it once I have it...
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: destination.player!.currentItem)
func playerDidFinishPlaying(note:NSNotification){
print("finished")
// close window/controller
}
Lastly, I know I'll need to remove the observer, but I'm not sure when or where to do so. Any help is greatly appreciated.

In order to "close" the controller, you should call dismissViewControllerAnimated(true, completion: nil)
So the code will look like:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: destination.player!.currentItem)
func playerDidFinishPlaying(note:NSNotification){
print("finished")
dismissViewControllerAnimated(true, completion: nil)
}
if your viewController is inside of a UINavigationController stack, you can also do:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: destination.player!.currentItem)
func playerDidFinishPlaying(note:NSNotification){
print("finished")
navigationController?.popViewControllerAnimated(true)
}
And for remove the observer, you can do within deinit{}:
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}

for #iOS 11 and swift 4.2 dismiss controller are not work so just add this key in your player setup code
if #available(iOS 11.0, *) {
self.playerVC?.exitsFullScreenWhenPlaybackEnds = true
}
if you wan to allow #iOS 10 as well then write this line.
if #available(iOS 11.0, *) {
self.playerVC?.exitsFullScreenWhenPlaybackEnds = true
}
NotificationCenter.default.addObserver(self, selector: #selector(self.playerItemDidReachEnd(notification:)), name: .AVPlayerItemDidPlayToEndTime, object:self.playerVC?.player!.currentItem)
func playerItemDidReachEnd(note:NSNotification){
print("finished")
dismissViewControllerAnimated(true, completion: nil)
}

Update for SWIFT 3:
Notes: The viewController where you are playing the audio needs: AVAudioPlayerDelegate
Also you dont need an observer
class myViewController: UIViewController, AVAudioPlayerDelegate {
var audioplayer = AVAudioPlayer()
override func viewDidAppear(_ animated: Bool) {
if soundsON{
let myFilePathString = Bundle.main.path(forResource: "backgroundSound", ofType: "mp3")
if let myFilePathString = myFilePathString
{
let myFilePathURL = URL(fileURLWithPath: myFilePathString)
do{
try audioplayer = AVAudioPlayer(contentsOf: myFilePathURL)
audioplayer.delegate = self
audioplayer.prepareToPlay()
audioplayer.play()
}catch{
print("error playing coin sound")
}
}
}
}
In this example the sound will play at viewDidAppear, and when it finishes it will call: audioPlayerDidFinishPlaying:
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
//Check if the sound that finishes comes from a certain AVAudioPlayer
if player == audioplayer{
print("The sound from -audioplayer- has finished")
// If you need to dismiss the VC:
dismiss(animated: true, completion: nil)
}
}

Related

Using swift I cant work out how to go to a new screen once video has stoped

I have an initial screen with a button on it which when you press it a video plays. Then once the film has ended I want the video to close and it to go to a different screen. At the moment I am able to make the button play the video and then when the video ends make the video close but it returns to the initial screen. Can some help? I have pasted my code below.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
let playerViewController = AVPlayerViewController()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func playButton(_ sender: AnyObject) {
let movieURL = Bundle.main.url(forResource: "video", withExtension: "mp4")!
let player = AVPlayer(url: movieURL as URL)
playerViewController.player = player
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerViewController.player?.currentItem)
self.present(playerViewController, animated: true) {
self.playerViewController.player!.play()
}
}
#objc func playerDidFinishPlaying(note: NSNotification) {
self.playerViewController.dismiss(animated: true)
}
}
What do you mean by "finished"?
is it mean the video is ended or user close the viewcontroller or other?
for when the video finish, you need to use NotificationCenter
func playVideo(url: URL) {
let playerItem = AVPlayerItem(asset: AVURLAsset(url: someVideoUrl))
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEndTime), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
self.player.replaceCurrentItem(with: playerItem)
self.player.play()
}
func playerItemDidPlayToEndTime() {
// load next video or something
}
for when user close AVPlayerViewController,
you can check AVPlayerViewControllerDelegate , it have several method that may fulfill your need

Automatically dismiss AVPlayer when video completes from ALL SCREENS

When my video completes, I want it to pull down the AVPlayer and return to the Main View Controller.
I also want to pull the video down from my external screen/display when that's connected.
How do I do this?
I've tried a few different answers on here and none of them have worked so far.
NOTE: Four is the name of my video
#IBAction func fourVideoPlayButton(_ sender: Any) {
if let path = Bundle.main.path(forResource: "Four", ofType: "mp4") {
let fourVideo = AVPlayer(url: URL(fileURLWithPath: path))
let fourVideoPlayer = AVPlayerViewController()
fourVideoPlayer.player = fourVideo
present(fourVideoPlayer, animated: true, completion: {
fourVideo.play()
})
}
}
You need to add observer to detect when player is finished playing by
NotificationCenter.default.addObserver(self, selector: Selector(("playerDidFinishPlaying:")),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: fourVideoPlayer.player.currentItem)
func playerDidFinishPlaying(note: NSNotification) {
fourVideoPlayer.dismiss(animated: true, completion: nil)
}
Hope this help!
In Swift 4.2,
let fourPlayerController = AVPlayerViewController()
#IBAction func fourVideoPlayButton(_ sender: Any) {
guard let path = Bundle.main.path(forResource: "Four", ofType:"mp4") else {
return
}
let fourVideoPlayer = AVPlayer(url: URL(fileURLWithPath: path))
fourPlayerController.player = fourVideoPlayer
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: fourPlayerController.player?.currentItem)
present(fourPlayerController, animated: true) {
fourVideoPlayer.play()
}
}
#objc func playerDidFinishPlaying(note: NSNotification) {
fourPlayerController.dismiss(animated: true, completion: nil)
fourPlayerController.dismiss(true, completion: nil)
fourPlayerController.view.removeFromSuperview()
self.presentedViewController?. dismiss(true, completion: nil)
}

Sync video in AVPlayerLayer and AVPlayerViewController

I'm working with AVPlayerto show the playing video using a URL in it. There are 2 parts to it:
1. Firstly, I've embedded the AVPlayer to a view's sublayer using AVPlayerLayer, i.e.
var player: AVPlayer?
func configure() {
let urlString = "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
if let url = URL(string: urlString) {
self.player = AVPlayer(url: url)
let playerLayer = AVPlayerLayer(player: self.player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
}
}
The above code is working fine and the video is playing.
2. Secondly, on a UIButton tap, I'm presenting a AVPlayerViewController using the same AVPlayer instance that I created earlier, i.e.
#IBAction func onTapVideoButton(_ sender: UIButton) {
self.player?.pause()
let controller = AVPlayerViewController()
controller.player = self.player
self.present(controller, animated: true) {
self.player?.play()
}
}
The problem I'm facing here is, after the AVPlayerViewController opens, the video stops playing but the audio still plays on.
What I want is to sync the video in both AVPlayerLayer and AVPlayerViewController.
I think there is a problem when sharing a player already created to the AVPlayerViewController. I'm not sure why is stoping but it wont happen if you create a new AVPlayer for that controller. A way to sync your player and your AVPlayerViewController could be like this:
First, you create a Notification Name that you'll use when the AVPlayerViewController is dismiss (apple does not give you a way to know when the user dismiss the AVPlayerViewController):
extension Notification.Name {
static let avPlayerDidDismiss = Notification.Name("avPlayerDidDismiss")
}
Then, you extend AVPlayerViewController to post this notification when is going to be dismiss and to send the time when the user left the video:
extension AVPlayerViewController {
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let seekTime = player?.currentTime() {
let userInfo = ["seekTime": seekTime]
NotificationCenter.default.post(name: .avPlayerDidDismiss, object: nil, userInfo: userInfo)
}
}
}
And in your ViewController you observe that notification, get the seekTime you want to go and use it to setup your avPlayer:
class ViewController: UIViewController {
var player: AVPlayer?
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
configure()
NotificationCenter.default.addObserver(self, selector: #selector(avPlayerDidDismiss), name: .avPlayerDidDismiss, object: nil)
}
func configure() {
self.player = getPlayer()
let playerLayer = AVPlayerLayer(player: self.player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
self.player?.play()
}
#IBAction func onTapVideoButton(_ sender: UIButton) {
self.player?.pause()
let controllerPlayer = getPlayer()
controllerPlayer.currentItem?.seek(to: self.player!.currentTime(), completionHandler: nil)
let controller = AVPlayerViewController()
controller.player = controllerPlayer
self.present(controller, animated: true, completion: {
controller.player?.play()
})
}
func getPlayer() -> AVPlayer {
let url = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!
return AVPlayer(url: url)
}
#objc
private func avPlayerDidDismiss(_ notification: Notification) {
if let seekTime = notification.userInfo?["seekTime"] as? CMTime {
player?.currentItem?.seek(to: seekTime, completionHandler: nil)
player?.play()
}
}
}
Cons: It will send the notification for every AVPlayerViewController. You use add you as an observer when you need this info. Hope it can help.

Close AVPlayer when movie is complete

I am making a simple iPad app to play a movie when a button is pressed. The movie plays and when the movie is finished I want to close AVPlayerView so it goes back to the main screen.
Currently when the video finishes it stays on the last frame.
My ViewController.Swift at the moment.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
//MARK : Properties
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//MARK: Actions
#IBAction func playButton(_ sender: AnyObject) {
let movieURL = Bundle.main.url(forResource: "ElephantSeals", withExtension: "mov")!
let player = AVPlayer(url: movieURL as URL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
// player.actionAtItemEnd = playerViewController.dismiss(animated: true)
}
}
As you can see, I think there might be something in actionAtItemEnd, but I'm not sure how to implement it.
Thank you.
This is working code in swift 5.3 and iOS 14.2, try this and let me know...:)
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
let playerViewController = AVPlayerViewController()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func playButton(_ sender: AnyObject) {
let movieURL = Bundle.main.url(forResource: "ElephantSeals", withExtension: "mp4")!
let player = AVPlayer(url: movieURL as URL)
playerViewController.player = player
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerViewController.player?.currentItem)
self.present(playerViewController, animated: true) {
self.playerViewController.player!.play()
}
}
#objc func playerDidFinishPlaying(note: NSNotification) {
self.playerViewController.dismiss(animated: true)
}
}
You can download sample project for same from here
https://github.com/deepakiosdev/AVPlayerViewControllerDemo
Swift 4
let playerController = AVPlayerViewController()
private func playVideo() {
guard let path = Bundle.main.path(forResource: "p810", ofType:"mp4") else {
debugPrint("video.m4v not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
playerController.player = player
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerController.player?.currentItem)
present(playerController, animated: true) {
player.play()
}
}
#objc func playerDidFinishPlaying(note: NSNotification) {
playerController.dismiss(animated: true, completion: nil)
}
Using NSNotificationCenter you can do this .
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: videoPlayer!.currentItem)
#objc func playerDidFinishPlaying(note: NSNotification) {
// here you can do your dismiss controller logic
AVPlayerViewController.dismiss(animated: true)
print("Video Finished")
}
here is objective c code
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(nextVideo:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerViewController.player.currentItem];
Invoke AVPlayerViewControllerDelegate.
In viewDidLoad initialize the delegate and implement this method
func playerViewControllerDidStopPictureInPicture(AVPlayerViewController) {
AVPlayerViewController.dismiss(animated: true)
}
https://developer.apple.com/reference/avkit/avplayerviewcontrollerdelegate

How to detect when AVPlayer video ends playing?

I'am using AVPlayer for playing local video file (mp4) in Swift.
Does anyone know how to detect when video finish with playing?
Thanks
To get the AVPlayerItemDidPlayToEndTimeNotification your object needs to be an AVPlayerItem.
To do so, just use the .currentItem property on your AVPlayer
Now you will get a notification once the video ends!
See my example:
let videoPlayer = AVPlayer(URL: url)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:",
name: AVPlayerItemDidPlayToEndTimeNotification, object: videoPlayer.currentItem)
func playerDidFinishPlaying(note: NSNotification) {
print("Video Finished")
}
Swift 3
let videoPlayer = AVPlayer(URL: url)
NotificationCenter.default.addObserver(self, selector: Selector(("playerDidFinishPlaying:")),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: videoPlayer.currentItem)
func playerDidFinishPlaying(note: NSNotification) {
print("Video Finished")
}
Don't forget to remove the Observer in your deinit
Swift 4, 5
NotificationCenter.default
.addObserver(self,
selector: #selector(playerDidFinishPlaying),
name: .AVPlayerItemDidPlayToEndTime,
object: videoPlayer.currentItem
)
Swift 3.0
let videoPlayer = AVPlayer(URL: url)
NotificationCenter.default.addObserver(self, selector:#selector(self.playerDidFinishPlaying(note:)),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
#objc func playerDidFinishPlaying(note: NSNotification){
print("Video Finished")
}
Swift 4.2 Version:
var player: AVPlayer!
//
//
// Configure Player
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let filepath: String? = Bundle.main.path(forResource: "selectedFileName", ofType: "mp4")
if let filepath = filepath {
let fileURL = URL.init(fileURLWithPath: filepath)
player = AVPlayer(url: fileURL)
let playerLayer = AVPlayerLayer(player: player)
// Register for notification
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidReachEnd),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: nil) // Add observer
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
}
}
// Notification Handling
#objc func playerItemDidReachEnd(notification: NSNotification) {
player.seek(to: CMTime.zero)
player.play()
}
// Remove Observer
deinit {
NotificationCenter.default.removeObserver(self)
}
For SWIFT 3.0
This is working fine
class PlayVideoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayVideoViewController.finishVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTimeNotification, object: nil)
}
func finishVideo()
{
print("Video Finished")
}
}
Swift 4.0
This one works for me. Thanks to #Channel
private func playVideo(fileURL: String) {
// Create RUL object
let url = URL(string: fileURL)
// Create Player Item object
let playerItem: AVPlayerItem = AVPlayerItem(url: url!)
// Assign Item to Player
let player = AVPlayer(playerItem: playerItem)
// Prepare AVPlayerViewController
let videoPlayer = AVPlayerViewController()
// Assign Video to AVPlayerViewController
videoPlayer.player = player
NotificationCenter.default.addObserver(self, selector: #selector(myViewController.finishVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
// Present the AVPlayerViewController
present(videoPlayer, animated: true, completion: {
// Play the Video
player.play()
})
}
#objc func finishVideo()
{
print("Video Finished")
}
If you fancy using Combine:
private var cancelBag: Set<AnyCancellable> = []
NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime)
.sink { _ in
player.seek(to: CMTime.zero)
player.play()
}
.store(in: &cancelBag)
2019
It's really this simple
NotificationCenter.default.addObserver(
self,
selector: #selector(fileComplete),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: nil
)
(It's fine for the object to be nil.)
and then
#objc func fileComplete() {
print("IT'S DONE!")
}
SWIFT 5 Update
The observer method with #objc function is not native. It is better to use event publisher in swift 5. Very simple.
Declare the following in the struct:
var pub = NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime)
Then on any view, add
.onReceive(pub) { (output) in
print("Video Finished")
}
Swift 3.0
let videoPlayer = AVPlayer(URL: url)
NotificationCenter.default.addObserver(self, selector:#selector(self.playerDidFinishPlaying(note:)),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
func playerDidFinishPlaying(note: NSNotification){
//Called when player finished playing
}
For SWIFT 3.0
Here 'fullUrl' is the URL of the video and make sure that there would be no space in the URL, You should replace 'Space' with '%20' so that URL will work file.
let videoURL = NSURL(string: fullUrl)
let player = AVPlayer(url: videoURL! as URL)
playerViewController.delegate = self
playerViewController.player = player
self.present(playerViewController, animated: false) {
self.playerViewController.player!.play()
NotificationCenter.default.addObserver(self, selector: #selector(yourViewControllerName.playerDidFinishPlaying), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
}
Add this below given method in your view controller.
func playerDidFinishPlaying(){
print("Video Finished playing in style")
}
I know there are a lot of accepted answers here...
But, another route might be to add a boundary time observer to your AVPlayer. You would have to have the duration of the video, which you can get from your player.currentItem, and then add it as your desired time boundary.
fileprivate var videoEndObserver: Any?
func addVideoEndObserver() {
guard let player = YOUR_VIDEO_PLAYER else { return }
// This is just in case you are loading a video from a URL.
guard let duration = player.currentItem?.duration, duration.value != 0 else {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { [weak self] in
self?.addVideoEndObserver()
})
return
}
let endTime = NSValue(time: duration - CMTimeMakeWithSeconds(0.1, duration.timescale))
videoEndObserver = player.addBoundaryTimeObserver(forTimes: [endTime], queue: .main, using: {
self.removeVideoEndObserver()
// DO YOUR STUFF HERE...
})
}
func removeVideoEndObserver() {
guard let observer = videoEndObserver else { return }
videoPlayer.player?.removeTimeObserver(observer)
videoEndObserver = nil
}
func shareEditedVedio() -> AVPlayer {
let editedVedioPlayer = AVPlayer(url: self.vedioData.vedioURLWithAddedSounds!)
NotificationCenter.default.addObserver(self, selector:#selector(self.playerDidFinishPlaying(note:)),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: editedVedioPlayer.currentItem)
return editedVedioPlayer
}
#objc func playerDidFinishPlaying(note: NSNotification){
//Called when player finished playing
}
In Swift 3 and RxSwift 3.5 all you have to do is:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.rx.notification(Notification.Name.AVPlayerItemDidPlayToEndTime)
.asObservable().subscribe(onNext: { [weak self] notification in
//Your action
}).addDisposableTo(disposeBag)
}
Using Combine, and also making sure the notification comes from the AVPlayerItem you are interested in and not just any. I am playing multiple items at once, so this would work in that scenario as well.
private var subscriptions: Set<AnyCancellable> = []
NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)
.receive(on: RunLoop.main)
.sink { [weak self] notification in
guard let item = notification.object as? AVPlayerItem else { return }
if item == self?.player.currentItem {
//.... Here you know it was the item you are interested in that played to end and not just any
}
}
.store(in: &subscriptions)
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: nil, queue: .main) { noti in
guard let item = noti.object as? AVPlayerItem else{
return
}
//DidPlayToEndTime
}
I had an issue with the Notification never getting called, setting the notification inside the presentation of the AVPlayerViewController solved it for me:
func presentVideo(url:URL) {
let player = AVPlayer(url: url)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
DispatchQueue.main.async {
playerViewController.player!.play()
//NOTE: The notification must be created here for it to work as expected
NotificationCenter.default.addObserver(self, selector: #selector(self.videoDidEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}
}
}
Another solution:
player.observe(\AVPlayer.actionAtItemEnd) { player, _ in
print("video did end")
}

Resources