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

后端 未结 2 1122
予麋鹿
予麋鹿 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:52

    I've reached the goal with the native AVPlayer

    1.Used AVFoundation:

    #import 
    

    2.Used property for player:

    @property (nonatomic) AVPlayer *avPlayer;
    

    3.Added video file into "Video" folder and added "Video" into project

    4.Initialized the player

    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.Subscribed for event - video did play to the end

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

    6.Resumed video playing from the very start in related method

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

提交回复
热议问题