我在macOS应用程序中创建了一个非常简单的AVPlayer。

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

    }

}

它基本上运行良好,但播放器在启动时自动播放,这是不应该的。即使我在playerView.player?.pause()的末尾添加viewDidLoad,它也会自动播放。
我做错什么了?

最佳答案

您至少应该将AVPlayer放在ViewWillAppear()函数中,暂停playerView.player将暂停整个视图,而不是暂停videoPlayer

videoPlayer.pause()

playerView.player = videoPlayer之后添加它应该可以工作;然后您的代码将是:
override func viewWillAppear() {
    super.viewWillAppear()

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

10-08 13:56