如何在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
        }
    }

推荐答案

Swift 3.x - 5.x

必需:import AVKitimport AVFoundation

AVFoundation framework is needed even if you use AVPlayer

如果您想使用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()

最好将此代码放入方法中:override func viewDidAppear(_ animated: Bool)或之后的某个位置.


Objective-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];

Ios相关问答推荐

自定义组件中的通用型-无法访问特定于收件箱的属性

自定义alert 未执行任何操作

如何创建自定义组件来接受(和传递)所有可能的Textfield参数?

为什么IOS多行文本输入在React原生纸张对话框中无法正常工作?

如何以编程方式触发 SwiftUI DatePicker?

CGPath intersection(_:using:) 和朋友(iOS 16 中的新功能)坏了?

Flutter 构建 ios 失败:运行 pod 安装时出错

如何在 Mac OS Ventura 中使用 Xcode 13

使用 Apollo 发布 iOS 应用程序时缺少推送通知权利

在 Swift 中映射 MySQL 数据

撤销 Apple 登录令牌以进行帐户删除过程

Xcode 13.4.1 (13F100)Command CodeSign 失败,退出代码非零我应该删除哪个证书?

SwiftUI - ScrollView 不显示底部文本

通过 tuist/XcodeProj 以编程方式将文件添加到本机目标

UIImageView 使用 CGAffineTransform 错误旋转

将图像保存到 Documents 目录并检索邮箱附件

UIScrollview 获取touch 事件

为什么 Safari 在使用 iOS 6 设备进行远程调试时显示No Inspectable Applications?

无法加载从带有标识符的包中的笔尖引用的图像

Xcode中的终端窗口?