Как воспроизводить видео внутри UIView без элементов управления, например, фона/обоев?

Целью является воспроизведение видеофайла (*.mp4) внутри UIView без элементов управления.

Он будет использоваться в качестве фона/обоев на ViewController и других элементах управления, то есть в режиме просмотра таблицы, текстовых полей, изображения будут отображаться над просмотром с воспроизведением видео.

Каков лучший способ сделать это? Спасибо вам

Ответы

Ответ 1

Я достиг цели с помощью нативного AVPlayer

1.Используется AVFoundation:

#import <AVFoundation/AVFoundation.h>

2.Использование для игрока:

@property (nonatomic) AVPlayer *avPlayer;

3. Добавленный видеофайл в папку "Видео" и добавленный "Видео" в проект

4.Инициализировал плеер

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"shutterstock_v885172.mp4" ofType:nil inDirectory:@"Video"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
self.avPlayer = [AVPlayer playerWithURL:fileURL];
self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;

AVPlayerLayer *videoLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
videoLayer.frame = self.view.bounds;
videoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:videoLayer];

[self.avPlayer play];

5. Подписано для события - видео до конца закончилось

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:[self.avPlayer currentItem]]; 

6. Воспроизведение видео с самого начала в связанном методе

- (void)itemDidFinishPlaying:(NSNotification *)notification {
    AVPlayerItem *player = [notification object];
    [player seekToTime:kCMTimeZero];
}

Ответ 2

Swift

В Swift это похоже. Добавьте видео в свой ресурс. Мой более полный ответ здесь.

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