Stefan
Stefan

Reputation: 936

Issues pausing / playing an AVPlayer

I have an AVPlayer that I want to pause and resume when it's tapped.

The way I decided to go about this is by utilizing a tapGestureRecognizer on the view that the AVPlayer is attached to.

when there is a tap a boolean, variable didSelect becomes true. When there is second tap, didSelect becomes false.

Interestingly enough, when I use

    if didSelect == false {
        player.play()
    }

    if didSelect == true {
        player.pause()
    }

in the AVPlayerItemDidPlayToEndTime notification, it works fine but only after the video complete. Which makes me wonder if there is some notification along the lines of AVPlayerItemIsPlaying but I haven't found anything.

Here's what the code looks like.

    playerView.layer.cornerRadius = playerView.bounds.width * 0.025

    guard let path = Bundle.main.path(forResource: "video", ofType:"mp4") else {
        debugPrint("video.m4v not found")
        return
    }

    let player = AVPlayer(url: URL(fileURLWithPath: path))

    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = playerView.frame
    playerLayer.frame = self.frame

    playerLayer.frame = playerView.bounds
    playerLayer.masksToBounds = true
    playerLayer.cornerRadius = playerView.bounds.width * 0.025

    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill


    self.playerView.layer.addSublayer(playerLayer)

        player.isMuted = true
        player.play()




    if didSelect == false {
        player.play()
    }

    if didSelect == true {
        player.pause()
    }

    //looper
    NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem, queue: nil)
    { notification in
        let t1 = CMTimeMake(5, 100)
        player.seek(to: t1)

        player.play()
    }

Upvotes: 0

Views: 1684

Answers (2)

Stefan
Stefan

Reputation: 936

I created a global reference to player

var player: AVPlayer?

and referenced that in a UITapGestureRecognizer function and now control the pausing / playing from there.

Upvotes: 1

webjunkie
webjunkie

Reputation: 1184

I experienced the same issue an ended up creating an AVPLayerViewController that embeds playblack controls into the video.

Here's the modified code, I hope it helps.

import AVKit
import AVFoundation

let avController = AVPlayerViewController()
avController.showsPlaybackControls = true

let player = AVPlayer(url: URL(fileURLWithPath: path))

let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = playerView.frame


playerLayer.frame = playerView.bounds
playerLayer.masksToBounds = true
playerLayer.cornerRadius = playerView.bounds.width * 0.025

playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

avController.player = playerLayer

avController.view.frame = playerView.bounds

self.playerView.addSubview(avController.view)

Upvotes: 0

Related Questions