首页 > 解决方案 > 在没有按钮的视图控制器上自动播放视频

问题描述

谁能告诉我我做错了什么?我已将所有内容正确并测试了代码,但每次在我的设备上运行应用程序时,视频都不会播放。它显示为暂停状态。我不知道为什么视频不会自动播放。

这是我的代码:

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)
    }


        }

标签: iosxcode

解决方案


只需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()
}

推荐阅读