How to play video inside a UIView without controls, like a background/wallpaper?

后端 未结 2 1127
予麋鹿
予麋鹿 2021-01-30 07:29

The goal is to playback video file (*.mp4) inside a UIView without controls.

It will serve as a background/wallpaper on the ViewController and other controls, i.e. table

2条回答
  •  无人共我
    2021-01-30 07:48

    Swift

    In Swift it is similar. Add the video to your resource bundle. My fuller answer is here.

    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: "SampleVideo_360x240_1mb", ofType: "mp4")
            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)
        }
    
        @IBAction func playVideoButtonTapped(_ sender: UIButton) {
            // play the video if the player is initialized
            player?.play()
        }
    }
    

提交回复
热议问题