AVPLAYER 不会显示在视图上但会播放声音

AVPLAYER won't show on the view but plays sound

所以我正在使用 AVFoundation 开发一个播放器,我可以让它播放,但它不会显示在视图中。谁能告诉我我缺少什么才能让它显示在视图上?

这是我的代码:

    self.playerUrl = NSURL(string: playerStr)!
    self.player = AVPlayer.playerWithURL(self.playerUrl)! as! AVPlayer
    self.playerLayer.frame = CGRectMake(0, 0, 200, 200)
    self.playerLayer = AVPlayerLayer(layer: self)
    self.playerLayer = AVPlayerLayer(player: player)
    self.view.layer.addSublayer(playerLayer)
    self.player.play()

我有以前使用 MPMoviePlayerController 的应用程序的代码,它已经过时(他们建议您使用 AVPlayer),我知道它可以工作。你可以试试。

    let url:NSURL = NSURL(string: playerStr)!
    self.moviePlayer = MPMoviePlayerController(contentURL: url)
    if let player = self.moviePlayer {
        player.view.frame = CGRect(x: 0, y: 50, width: self.view.frame.size.width, height: self.view.frame.size.height/2 + 50)
        player.view.sizeToFit()
        player.scalingMode = MPMovieScalingMode.None
        player.movieSourceType = MPMovieSourceType.File
        player.repeatMode = MPMovieRepeatMode.One;
        self.view.addSubview(player.view)
        player.play()
    }

这是您的工作代码:

let videoURL = NSURL(string: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(URL: videoURL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()

在您的代码中,您在这一行中犯了错误:

self.player = AVPlayer.playerWithURL(self.playerUrl)! as! AVPlayer

只需将其更改为:

self.player = AVPlayer(URL: playerUrl)

它会很好地工作。