MPMoviePlayerController在5秒后停止播放 - Swift

时间:2015-03-31 01:49:33

标签: ios swift mpmovieplayercontroller

我有一个视频,我尝试使用MPMoviePlayerController进行播放并且加载正常,但在5秒后切断。我找到了这篇文章,但它并不适用于swift。

MPMoviePlayerController stops playing the video after 5s

这是我的代码。

import MediaPlayer




class ViewController: UIViewController  {


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.



    var moviePlayer: MPMoviePlayerController?



let url = NSURL(string: "http://path/to/video.m3u8")

    moviePlayer = MPMoviePlayerController(contentURL: url)

    if let player = moviePlayer {

        player.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
        player.view.sizeToFit()
        player.scalingMode = MPMovieScalingMode.None


        player.movieSourceType = MPMovieSourceType.Streaming
        //player.repeatMode = MPMovieRepeatMode.One


        player.play()

        self.view.addSubview(player.view)

        NSNotificationCenter.defaultCenter().addObserver(
            self,
            selector: "metadataUpdated",
            name: MPMoviePlayerTimedMetadataUpdatedNotification,
            object: nil)

    }

}

1 个答案:

答案 0 :(得分:2)

你的moviePlayer可能会超出范围吗?你试过把它变成一个成员变量吗?

moviePlayerviewDidLoad的局部变量,所以一旦该函数完成,我就看不出为什么你的播放器不会被解除分配的原因。

如果你把它变成一个类的变量,它的生命周期将被扩展到与你的类的生命周期相匹配。

类似

class ViewController: UIViewController {

var player: MPMoviePlayerController?

    override func viewDidLoad() {
        // ...
        self.player = MPMoviePlayerController(contentURL: url) // won't go out of scope at end of viewDidLoad()
        // ...
    }