Search code examples
swiftavfoundationavplayeravplayerviewcontrolleravkit

AVPlayer autoplays but should not (Swift)


I’ve created a very simple AVPlayer within a macOS app.

import Cocoa
import AVKit
import AVFoundation

class ViewController: NSViewController {

@IBOutlet var playerView: AVPlayerView!

override func viewDidLoad() {

    super.viewDidLoad()

    let videoPath = URL(fileURLWithPath: "myPath/myFile.mp4")
    let videoPlayer = AVPlayer(url: videoPath)
    playerView.player = videoPlayer

    }

}

It basically works fine, but the player plays automatically on launch, which it should not. Even when I add playerView.player?.pause() at the end of viewDidLoad, it autoplays.

What am I doing wrong?


Solution

  • You should at least put your AVPlayer in the ViewWillAppear() function, and pausing playerView.player would pause your entire view — instead pause videoPlayer:

    videoPlayer.pause()
    

    Adding that after playerView.player = videoPlayer should work; your code would then be:

    override func viewWillAppear() {
        super.viewWillAppear()
    
        let videoPath = URL(fileURLWithPath: "myPath/myFile.mp4")
        let videoPlayer = AVPlayer(url: videoPath)
        playerView.player = videoPlayer
        videoPlayer.pause()
    }