如何在Swift中使用AVPlayerViewController(AVKit)播放视频


164

如何在Swift中使用AV Kit Player View Controller播放视频?

override func viewDidLoad() {
        super.viewDidLoad()
        let videoURLWithPath = "http://****/5.m3u8"
        let videoURL = NSURL(string: videoURLWithPath)
        playerViewController = AVPlayerViewController()

        dispatch_async(dispatch_get_main_queue()) {
            self.playerViewController?.player = AVPlayer.playerWithURL(videoURL) as AVPlayer
        }
    }

对于使用AVPlayer(没有控件),请参见此答案
Suragch '17

Answers:


532

雨燕3.x-5.x

必要:导入AVKit导入AVFoundation

即使使用AVPlayer,也需要AVFoundation框架

如果要使用AVPlayerViewController

let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
    playerViewController.player!.play()
}

或只是AVPlayer

let videoURL = URL(string: "https://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()

最好将此代码放入方法中:覆盖func viewDidAppear(_动画:Bool)或之后的某个位置。


目标C

AVPlayerViewController

NSURL *videoURL = [NSURL URLWithString:@"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];
AVPlayer *player = [AVPlayer playerWithURL:videoURL];
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
playerViewController.player = player;
[self presentViewController:playerViewController animated:YES completion:^{
  [playerViewController.player play];
}];

或只是AVPlayer

NSURL *videoURL = [NSURL URLWithString:@"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];
AVPlayer *player = [AVPlayer playerWithURL:videoURL];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
playerLayer.frame = self.view.bounds;
[self.view.layer addSublayer:playerLayer];
[player play];

@pikis感谢您的代码示例。奇怪,我们尝试编写AVPlayerController并在以下位置获得SIGABRT:[self presentViewController:playerViewController动画:是完成:无];
Praxiteles

@Praxiteles,它可在iOS8或更高版本上运行,也许是原因。
pkis 2015年

8
我也需要导入AVFoundation
Rich Fox

1
@ Nick89,AVPlayer可使用直接链接正常工作,但是如果您需要使用YouTube,Vimeo等具有间接链接的服务,则应使用其自己的库或SDK。(例如,对于YouTube:指南)。
pkis

2
说明的顺序很重要,我也需要导入AVKit
htafoya

30

试试这个,绝对适合 Swift 2.0

 let player = AVPlayer(URL: url)
    let playerController = AVPlayerViewController()

    playerController.player = player
    self.addChildViewController(playerController)
    self.view.addSubview(playerController.view)
    playerController.view.frame = self.view.frame

    player.play()  

1
谢谢。addChildViewController使它恰好嵌入了我想要的内容。:)
SDW

1
嵌入确实可以正常工作,但是您将如何处理方向变化?让玩家说发生在纵向屏幕的一半,视图控制器仅支持肖像,但视频可以在人像可以看到最喜欢的应用程序做电子商务.. YouTube上,VIMEO等
阿比德·侯赛因

注意:addChildViewController是必需的。我尝试过没有它,然后几乎可以正常工作-它可以播放一次,并且可以全屏显示。但它不会再次播放或退出全屏模式。因此,子视图控制器是必需的。
n13

self.addChildViewController(playerController)现在self.addChild(playerController)FYI
Marquis103

12

试试这个

var player:AVPlayer!
var avPlayerLayer:AVPlayerLayer = AVPlayerLayer(player: player)
avPlayerLayer.frame = CGRectMake(your frame)
self.view.layer .addSublayer(avPlayerLayer)
var steamingURL:NSURL = NSURL(string:playerURL)
player = AVPlayer(URL: steamingURL)
player.play()

当我运行此代码时,我得到了空视图控制器
orazz

@Oneperson您设置了avPlayerLayer框架?
Ramesh 2014年

1
@Oneperson好的将其设置为avPlayerLayer.frame = CGRectMake(50,50,100,100)
Ramesh

代码var player:AVPlayer!var playerItem:AVPlayerItem !; var avPlayerLayer:AVPlayerLayer = AVPlayerLayer(player:player)avPlayerLayer.frame = CGRectMake(50,50,100,100)self.view.layer .addSublayer(avPlayerLayer)let videoURLWithPath =“ http://*****/45.m3u8” var steamingURL:NSURL = NSURL(字符串:videoURLWithPath)播放器= AVPlayer(URL:steamingURL)player.play()代码
orazz 2014年

@Oneperson edge.tolkun.tv/45.m3u8无法正常工作。您能否提供完整的网址
Ramesh 2014年

11

Swift 3.0完整源代码:

import UIKit
    import AVKit
    import AVFoundation

    class ViewController: UIViewController,AVPlayerViewControllerDelegate
    {
        var playerController = AVPlayerViewController()


        @IBAction func Play(_ sender: Any)
        {
            let path = Bundle.main.path(forResource: "video", ofType: "mp4")

            let url = NSURL(fileURLWithPath: path!)

            let player = AVPlayer(url:url as URL)

            playerController = AVPlayerViewController()


            NotificationCenter.default.addObserver(self, selector: #selector(ViewController.didfinishplaying(note:)),name:NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)

            playerController.player = player

            playerController.allowsPictureInPicturePlayback = true

            playerController.delegate = self

            playerController.player?.play()

            self.present(playerController,animated:true,completion:nil)
        }

        func didfinishplaying(note : NSNotification)
        {
            playerController.dismiss(animated: true,completion: nil)
            let alertview = UIAlertController(title:"finished",message:"video finished",preferredStyle: .alert)
            alertview.addAction(UIAlertAction(title:"Ok",style: .default, handler: nil))
            self.present(alertview,animated:true,completion: nil)
        }


        func playerViewController(_ playerViewController: AVPlayerViewController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) {
                let currentviewController =  navigationController?.visibleViewController

                if currentviewController != playerViewController
                {
                    currentviewController?.present(playerViewController,animated: true,completion:nil)
                }


            }
    }

你好罗纳克,谢谢你迅速介绍观察员来处理视频的结尾!我没有通过使用答案顶部的答案(第一个代码段)提供的代码创建AVPlayerViewController来使其工作(有什么区别)?为了使您的方法中的观察者正常工作,我错过了或应该执行哪些措施?
Manu

6

目标c

这仅适用于 Xcode 7

转到.h文件并导入AVKit/AVKit.hAVFoundation/AVFoundation.h。然后去.m文件并添加以下代码:

NSURL *url=[[NSBundle mainBundle]URLForResource:@"arreg" withExtension:@"mp4"];
AVPlayer *video=[AVPlayer playerWithURL:url];
AVPlayerViewController *controller=[[AVPlayerViewController alloc]init];
controller.player=video;
[self.view addSubview:controller.view];
controller.view.frame=self.view.frame;
[self addChildViewController:controller];
[video play];

4

使用MPMoviePlayerController:

 import UIKit
 import MediaPlayer

 class ViewController: UIViewController {

     var streamPlayer : MPMoviePlayerController =  MPMoviePlayerController(contentURL: NSURL(string:"video url here"))
     override func viewDidLoad() {
         super.viewDidLoad()
         streamPlayer.view.frame = self.view.bounds
         self.view.addSubview(streamPlayer.view)

         streamPlayer.fullscreen = true
         // Play the movie!
         streamPlayer.play()
}
}

使用AVPlayer:

import AVFoundation

var playerItem:AVPlayerItem?
var player:AVPlayer?

override func viewDidLoad() {
        super.viewDidLoad() 
      let url = NSURL(string: "url of the audio or video") 
      playerItem = AVPlayerItem(URL: url!)
      player=AVPlayer(playerItem: playerItem!)
      let playerLayer=AVPlayerLayer(player: player!)
      playerLayer.frame=CGRectMake(0, 0, 300, 50)
      self.view.layer.addSublayer(playerLayer)
}

我有一个播放按钮来处理按钮点击。

playButton.addTarget(self, action: "playButtonTapped:", forControlEvents: .TouchUpInside)

func playButtonTapped(sender: AnyObject) {
        if player?.rate == 0
        {
            player!.play()
            playButton.setImage(UIImage(named: "player_control_pause_50px.png"), forState: UIControlState.Normal)
        } else {
            player!.pause()
            playButton.setImage(UIImage(named: "player_control_play_50px.png"), forState: UIControlState.Normal)
        }
    }

我添加了一个监听AVPlayerItemDidPlayToEndTimeNotification的观察者。

override func viewWillAppear(animated: Bool) {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "finishedPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)
    }

override func viewWillDisappear(animated: Bool) {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

视频/音频播放完成后,重置按钮图像和通知

  func finishedPlaying(myNotification:NSNotification) {
        playButton.setImage(UIImage(named: "player_control_play_50px.png"), forState: UIControlState.Normal)

        let stopedPlayerItem: AVPlayerItem = myNotification.object as! AVPlayerItem
        stopedPlayerItem.seekToTime(kCMTimeZero)
    }

2
MPMoviePlayerController已弃用,我们可能不再应该使用它。
天行者

您能否举一个不使用URL的示例,例如使用本地视频。
nyxee

4

iOS10 / Swift3 / Xcode 8中的错误(?!)?

if let url = URL(string: "http://devstreaming.apple.com/videos/wwdc/2016/102w0bsn0ge83qfv7za/102/hls_vod_mvp.m3u8"){
    let playerItem = AVPlayerItem(url: url)
    let player = AVPlayer(playerItem: playerItem)
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame=CGRect(x: 10, y: 10, width: 300, height: 300)
    self.view.layer.addSublayer(playerLayer)
}

不起作用(空矩形...)

这有效:

if let url = URL(string: "http://devstreaming.apple.com/videos/wwdc/2016/102w0bsn0ge83qfv7za/102/hls_vod_mvp.m3u8"){

            let player = AVPlayer(url: url)
            let controller=AVPlayerViewController()
            controller.player=player
            controller.view.frame = self.view.frame
            self.view.addSubview(controller.view)
            self.addChildViewController(controller)
            player.play()
        }

相同的网址...


添加此行: player.play()之后:self.view.layer.addSublayer(playerLayer)然后重试
orazz

4

斯威夫特3:

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    @IBOutlet weak var viewPlay: UIView!
    var player : AVPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        let url : URL = URL(string: "http://static.videokart.ir/clip/100/480.mp4")!
        player = AVPlayer(url: url)
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.viewPlay.bounds
        self.viewPlay.layer.addSublayer(playerLayer)

    }

    @IBAction func play(_ sender: Any) {
        player?.play()
    }

    @IBAction func stop(_ sender: Any) {
        player?.pause()
    }

}

您在答案中的何处使用了AVPlayerViewController
AnBisw

1

这在 Swift 5中对我有用

刚刚将示例视频从“ 示例视频”添加到项目中

添加了用于播放来自网站和本地视频的操作按钮,并带有以下快速代码示例

import UIKit
import AVKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //TODO : Make Sure Add and copy "SampleVideo.mp4" file in project before play
    }

    @IBAction func playWebVideo(_ sender: Any) {

        guard let url = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4") else {
            return
        }
        // Create an AVPlayer, passing it the HTTP Live Streaming URL.
        let player = AVPlayer(url: url)
        let controller = AVPlayerViewController()
        controller.player = player
        present(controller, animated: true) {
            player.play()
        }
    }

    @IBAction func playLocalVideo(_ sender: Any) {

        guard let path = Bundle.main.path(forResource: "SampleVideo", ofType: "mp4") else {
            return
        }
        let videoURL = NSURL(fileURLWithPath: path)

        // Create an AVPlayer, passing it the local video url path
        let player = AVPlayer(url: videoURL as URL)
        let controller = AVPlayerViewController()
        controller.player = player
        present(controller, animated: true) {
            player.play()
        }
    }

}

0

斯威夫特5

  @IBAction func buttonPressed(_ sender: Any) {
    let videoURL = course.introductionVideoURL
    let player = AVPlayer(url: videoURL)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player

    present(playerViewController, animated: true, completion: {

        playerViewController.player!.play()
    })

//这里的课程包括一个模型文件,我在其中提供了url,因此我使用课程函数从模型中调用该函数。

//另外,IntroductionVideoUrl是我在模型内部声明的URL。

 var introductionVideoURL: URL

另外,您也可以使用下面的代码来代替从模型中调用函数

替换此代码

  let videoURL = course.introductionVideoURL

  guard let videoURL = URL(string: "https://something.mp4) else {
        return

0
let videoUrl = //URL: Your Video URL

//Create player first using your URL
let yourplayer = AVPlayer(url: videoUrl)

//Create player controller and set it’s player
let playerController = AVPlayerViewController()
playerController.player = yourplayer


//Final step To present controller  with player in your view controller
present(playerController, animated: true, completion: {
   playerController.player!.play()
})

0

斯威夫特5.0

从@ingconti答案改进。这对我有用。

 if let url = URL(string: "urUrlString"){
            let player = AVPlayer(url: url)
            let avController = AVPlayerViewController()
            avController.player = player
            // your desired frame
            avController.view.frame = self.view.frame
            self.view.addSubview(avController.view)
            self.addChild(avController)
            player.play()
        }

0

迅捷5+

首先,您必须在视图控制器内部全局定义2个变量。

var player: AVPlayer!
var playerViewController: AVPlayerViewController!

在这里,我将播放器添加到所需的视图。

@IBOutlet weak var playerView: UIView!

然后将以下代码添加到viewDidLoad方法。

let videoURL = URL(string: "videoUrl")
self.player = AVPlayer(url: videoURL!)
self.playerViewController = AVPlayerViewController()
playerViewController.player = self.player
playerViewController.view.frame = self.playerView.frame
playerViewController.player?.pause()
self.playerView.addSubview(playerViewController.view)

如果您未全局定义播放器playerViewController,则将无法嵌入播放器。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.