0

I am playing video in videoView using AVPLayer but when app enters in background mode and again open the app then video is pause.

func playVideo() {

    if let filePath = Bundle.main.path(forResource: "Audios/copy1", ofType:"mp4") {

        let filePathUrl = NSURL.fileURL(withPath: filePath)

        videoPlayer = AVPlayer(url: filePathUrl)

        let playerLayer = AVPlayerLayer(player: videoPlayer)

        playerLayer.frame = self.videoView.bounds
        playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill

        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.videoPlayer?.currentItem, queue: nil) { (_) in
            self.videoPlayer?.seek(to: kCMTimeZero)
            self.videoPlayer?.play()
            self.videoPlayer.rate = 0.5
            self.videoPlayer.actionAtItemEnd = .none
        }

        self.videoView.layer.addSublayer(playerLayer)
        videoPlayer?.play()
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Umair Shams
  • 39
  • 1
  • 7

1 Answers1

0

Yes it is possible, but you must set up things correctly.

  1. You must configure your AVAudioSession correctly
  2. Disconnect the AVPlayer from your presentation when going in background

For the first point you must set Audio background mode to on and configure the audio session:

    do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            let _ = try AVAudioSession.sharedInstance().setActive(true)
        } catch let error as NSError {
            print("an error occurred when audio session category.\n \(error)")
        }

For the second:

func applicationDidEnterBackground(_ application: UIApplication) {

    // Disconnect the AVPlayer from the presentation when entering background

    // If presenting video with AVPlayerViewController
    playerViewController.player = nil

    // If presenting video with AVPlayerLayer
    playerLayer.player = nil
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Reconnect the AVPlayer to the presentation when returning to foreground

    // If presenting video with AVPlayerViewController
    playerViewController.player = player

    // If presenting video with AVPlayerLayer
    playerLayer.player = player
}

For more info check those documents:
link1
link2
link3

Andrea
  • 26,120
  • 10
  • 85
  • 131