ios - 在没有按钮的视图控制器上自动播放视频
问题描述
谁能告诉我我做错了什么?我已将所有内容正确并测试了代码,但每次在我的设备上运行应用程序时,视频都不会播放。它显示为暂停状态。我不知道为什么视频不会自动播放。
这是我的代码:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVPlayer?
@IBOutlet weak var videoViewContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
initializeVideoPlayerWithVideo()
}
func initializeVideoPlayerWithVideo() {
// get the path string for the video from assets
let videoString:String? = Bundle.main.path(forResource: "BackgroundAppVideo", ofType: "mov")
guard let unwrappedVideoPath = videoString else {return}
// convert the path string to a url
let videoUrl = URL(fileURLWithPath: unwrappedVideoPath)
// initialize the video player with the url
self.player = AVPlayer(url: videoUrl)
// create a video layer for the player
let layer: AVPlayerLayer = AVPlayerLayer(player: player)
// make the layer the same size as the container view
layer.frame = videoViewContainer.bounds
// make the video fill the layer as much as possible while keeping its aspect size
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
// add the layer to the container view
videoViewContainer.layer.addSublayer(layer)
}
}
解决方案
只需self.player?.play()
在最后添加。作为
func initializeVideoPlayerWithVideo() {
// get the path string for the video from assets
let videoString:String? = Bundle.main.path(forResource: "BackgroundAppVideo", ofType: "mov")
guard let unwrappedVideoPath = videoString else {return}
// convert the path string to a url
let videoUrl = URL(fileURLWithPath: unwrappedVideoPath)
// initialize the video player with the url
self.player = AVPlayer(url: videoUrl)
// create a video layer for the player
let layer: AVPlayerLayer = AVPlayerLayer(player: player)
// make the layer the same size as the container view
layer.frame = videoViewContainer.bounds
// make the video fill the layer as much as possible while keeping its aspect size
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
// add the layer to the container view
videoViewContainer.layer.addSublayer(layer)
self.player?.play()
}
推荐阅读
- actionscript-3 - 从 Flex - mxml(动作脚本)迁移到另一种技术
- django - 从外部模型在 django 中创建 get_full_name
- java - 我应该如何重构此方法以尊重不超过 2 或 3 个参数的 Uncle Bob 规则?
- python - KeyError("单词 '%s' 不在词汇表中" % word)
- android - ContentResolver 插入 MediaStore.Audio.Media.EXTERNAL_CONTENT_URI 错误
- css - IE 11 css-vars-ponyfill 仅支持 :root 变量,但不支持内联变量
- python - Django 显示相关名称列表中的第一项
- terraform - 使用共享映像库的多租户部署
- php - 为什么在将值插入外键字段时收到外键冲突错误。插入的值与引用表中的主键匹配
- intellij-idea - IntelliJ 不是为 Scala 自动加载包