iOS Video Backgrounds
First things first, import the MediaPlayer framework:
@import MediaPlayer;
Next, we create a new MPMoviePlayerController instance within our viewDidLoad: method.
NSURL *videoURL = [[NSBundle mainBundle] URLForResource:@"video" withExtension:@"mov"]; self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
self.moviePlayer.controlStyle = MPMovieControlStyleNone; self.moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
self.moviePlayer.view.frame = self.view.frame;[self.view insertSubview:self.moviePlayer.view atIndex:0];
[self.moviePlayer play];
While we’re in viewDidLoad:, let’s go ahead and add a notification handler to help us loop the video.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loopVideo) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
Time to set up that loopVideo function we’re calling in the above block.
- (void)loopVideo { [self.moviePlayer play]; }
And we’re done! Now all that’s left to do is throw a few UI elements on top.
Note: MPMoviePlayerController is deprecated in iOS 9.
So for ios9 and above use AVPlayer
| ||
override func viewDidLoad() { | ||
super.viewDidLoad() | ||
// Load the video from the app bundle. | ||
let videoURL: NSURL = NSBundle.mainBundle().URLForResource("video", withExtension: "mov")! | ||
player = AVPlayer(URL: videoURL) | ||
player?.actionAtItemEnd = .None | ||
player?.muted = true | ||
let playerLayer = AVPlayerLayer(player: player) | ||
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill | ||
playerLayer.zPosition = -1 | ||
playerLayer.frame = view.frame | ||
view.layer.addSublayer(playerLayer) | ||
player?.play() | ||
//loop video | ||
NSNotificationCenter.defaultCenter().addObserver(self, | ||
selector: "loopVideo", | ||
name: AVPlayerItemDidPlayToEndTimeNotification, | ||
object: nil) | ||
} | ||
func loopVideo() { | ||
player?.seekToTime(kCMTimeZero) | ||
player?.play() | ||
} | ||
Comments
Post a Comment