Objc - how to add a video player inside a UIView like this?
Solution 1
You can add a video player into your UIView
using MPMoviePlayerController
.
Here is Apple sample code which does just like this. It can stream a video from internet as well as play a local movie file.
You can change the playback controls by changing the moviePlayer controlStyle
property.
You can find the sample code from the link below
http://developer.apple.com/library/ios/#samplecode/MoviePlayer_iPhone/Introduction/Intro.html
Solution 2
The MPMoviePlayerController is deprecated from iOS 9. You can insert a video into iOS project with AVPlayerViewController now.
For example:
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
...
@property (nonatomic, retain) AVPlayerViewController *playerViewController;
...
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *stringVideoName = @"video.m4v";
NSString *stringVideoPath = [[NSBundle mainBundle] pathForResource:stringVideoName ofType:nil];
NSAssert(stringVideoPath, @"Expected not nil video file");
NSURL *urlVideoFile = [NSURL fileURLWithPath:stringVideoPath];
NSAssert(urlVideoFile, @"Expected not nil video url");
_playerViewController = [[AVPlayerViewController alloc] init];
_playerViewController.player = [AVPlayer playerWithURL:urlVideoFile];
_playerViewController.view.frame = self.view.bounds;
_playerViewController.showsPlaybackControls = YES;
[self.view addSubview:_playerViewController.view];
self.view.autoresizesSubviews = YES;
}
Comments
-
yellow almost 2 years
This player only have 2 buttons,play/pause and fullscreen,it looks like a
system player
,so fast and simple.I used
UIWebView and HTML5
inside the UIView,but UIWebView is so slow and can not play without fullscreen.If this player is a
UIObject
or some UIView things,how can I add it?thanks~
-
yellow over 11 yearsthank you viktoR,I got it with
MPMoviePlayerController
,but still have a problem,when my view with video push another view,the video could not stop and sound playing. -
sunhsiv over 11 years@yellow, before you push another view, stop
MPMoviePlayerController
,[myMoviePlayer stop]
will do the trick. Or if you just want to pause the video, you can use[myMoviePlayer pause]
. Go throughMPMoviePlayerController
class reference here -
smoothumut over 8 yearsjust copied and pasted, and it works great. thanks a lot
-
Chandni over 6 yearsI need to play youtube url so I write my nsurl in urlVideoFile. but noting is displaying on my view. pls suggest.