I am trying to play video inside a UIView
, so my first step was to add a class for that view and start playing a movie in it using this code:
- (IBAction)movie:(id)sender{
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath = [bundle pathForResource:@"Movie" ofType:@"m4v"];
NSURL *movieURL = [[NSURL fileURLWithPath:moviePath] retain];
MPMoviePlayerController *theMovie = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
theMovie.scalingMode = MPMovieScalingModeAspectFill;
[theMovie play];
}
But this just crashes the app when using this method inside it's own class, but is fine elsewhere. Does anyone know how to play video inside a view? and avoid it being full screen?
Looking at your code, you need to set the frame of the movie player controller's view, and also add the movie player controller's view to your view. Also, don't forget to add MediaPlayer.framework to your target.
Here's some sample code:
The best way is to use layers insted of views:
Don't forget to add frameworks:
You cannot play a video inside a view. It has to be played fullscreen.
As of the 3.2 SDK you can access the view property of
MPMoviePlayerController
, modify its frame and add it to your view hierarchy.There's an example here: http://www.devx.com/wireless/Article/44642/1954
Swift
This is a self contained project so that you can see everything in context.
Layout
Create a layout like the following with a
UIView
and aUIButton
. TheUIView
will be the container in which we will play our video.Add a video to the project
If you need a sample video to practice with, you can get one from sample-videos.com. I'm using an mp4 format video in this example. Drag and drop the video file into your project. I also had to add it explicitly into the bundle resources (go to Build Phases > Copy Bundle Resources, see this answer for more).
Code
Here is the complete code for the project.
Notes
AVPlayerItem
.AVFoundation
andAVPlayer
, then you have to build all of your own controls. If you want full screen video playback, you can useAVPlayerViewController
. You will need to importAVKit
for that. It comes with a full set of controls for pause, fast forward, rewind, stop, etc. Here and here are some video tutorials.MPMoviePlayerController
that you may have seen in other answers is deprecated.Result
The project should look like this now.