Skip to content

Instantly share code, notes, and snippets.

@fabiosoft
Last active January 7, 2021 10:21
Show Gist options
  • Save fabiosoft/a488f38ad8e6ec5fec5a212dec929b5d to your computer and use it in GitHub Desktop.
Save fabiosoft/a488f38ad8e6ec5fec5a212dec929b5d to your computer and use it in GitHub Desktop.
AVPlayer Programmatically
@interface ViewController ()
@property (nonatomic, strong) AVPlayer *videoPlayer;
@property (nonatomic, strong) AVPlayerItem *playerItem;
@property (nonatomic, strong) AVPlayerLayer *layer;
@end
@implementation ViewController
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
// remote file from server:
NSURL *url = [[NSURL alloc] initWithString:@"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"];
AVURLAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
self.playerItem = [[AVPlayerItem alloc] initWithAsset:avAsset];
self.videoPlayer = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
self.layer = [AVPlayerLayer playerLayerWithPlayer: self.videoPlayer];
self.layer.frame = self.view.layer.bounds;
UIView *newView = [[UIView alloc] initWithFrame:self.view.bounds];
[newView.layer addSublayer:self.layer];
[self.view addSubview:newView];
[self.videoPlayer play];
}
@end
import AVFoundation
class ViewController {
private var videoPlayer: AVPlayer?
private var playerItem: AVPlayerItem?
private var layer: AVPlayerLayer?
func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// remote file from server:
let url = URL(string: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4")
var avAsset: AVURLAsset? = nil
if let url = url {
avAsset = AVURLAsset(url: url, options: nil)
}
if let avAsset = avAsset {
playerItem = AVPlayerItem(asset: avAsset)
}
videoPlayer = AVPlayer(playerItem: playerItem)
layer = AVPlayerLayer(player: videoPlayer)
layer?.frame = view.layer.bounds
let newView = UIView(frame: view.bounds)
if let layer = layer {
newView.layer.addSublayer(layer)
}
view.addSubview(newView)
videoPlayer?.play()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment