小编典典

在Swift中从服务器播放视频文件

swift

我正在尝试使用Swift从服务器播放视频。

我已经导入了 MediaPlayer 框架,这是我的代码:

import UIKit
import MediaPlayer

class VideoViewController: UIViewController {

   override func viewDidLoad() {
        super.viewDidLoad()

        var url:NSURL = NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")        
        var moviePlayer = MPMoviePlayerController(contentURL: url)

        moviePlayer.view.frame = CGRect(x: 20, y: 100, width: 200, height: 150)        
        self.view.addSubview(moviePlayer.view)

        moviePlayer.fullscreen = true        
        moviePlayer.controlStyle = MPMovieControlStyle.Embedded        
   }
}

当我在模拟器中运行时,我只会看到一个黑匣子,但是无论从哪里尝试加载视频,都无法播放视频。

更新

这是当前代码

var url:NSURL = NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")

var moviePlayer = MPMoviePlayerController(contentURL: url)

moviePlayer.view.frame = CGRect(x: 20, y: 100, width: 200, height: 150)        
moviePlayer.movieSourceType = MPMovieSourceType.File

self.view.addSubview(moviePlayer.view)        
moviePlayer.prepareToPlay()
moviePlayer.play()

这段代码有趣地播放了大约2秒钟的视频,然后再次变黑!


阅读 364

收藏
2020-07-07

共1个答案

小编典典

更新2019,Swift 4:

在iOS 9.0中不推荐使用MPMovieControlStyle”:在AVKit中使用AVPlayerViewController。

因此,根据建议,我们对其进行更改。以下是2016年的原始答案。

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        let url = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!

        playVideo(url: url)
    }

    func playVideo(url: URL) {
        let player = AVPlayer(url: url)

        let vc = AVPlayerViewController()
        vc.player = player

        self.present(vc, animated: true) { vc.player?.play() }
    }
}

解决了:

import UIKit
import MediaPlayer

class VideoViewController: UIViewController {

   var moviePlayer:MPMoviePlayerController!

   override func viewDidLoad() {
      super.viewDidLoad()

      let url:NSURL = NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")

      moviePlayer = MPMoviePlayerController(contentURL: url)
      moviePlayer.view.frame = CGRect(x: 20, y: 100, width: 200, height: 150)

      self.view.addSubview(moviePlayer.view)
      moviePlayer.fullscreen = true

      moviePlayer.controlStyle = MPMovieControlStyle.Embedded

   }
}
2020-07-07