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

时间:2015-08-05 19:31:03

标签: ios swift avplayer

所以我正在使用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()

2 个答案:

答案 0 :(得分:1)

这是您的工作代码:

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)

它会正常工作。

答案 1 :(得分:0)

我有一个以前使用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()
    }