Tweaking the Video Player in IOS4


So, after some messing around a bit, I’ve come up with some nice code (thanks for the information on getting it working in IOS4, Joe) that only adds the video player to the view when the user presses the “play video” button, then removes it once the video is done.

I did this because I noticed that the video immediately begins to play on loading, and the user does not always want that to occur.

Thus, in MediaPlayerViewController.m

- (void)viewDidLoad {
       [super viewDidLoad];
	[[NSNotificationCenter defaultCenter] addObserver:self
	NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"Layers" ofType:@"m4v"];
	if (moviePath) {
		NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
		moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL];
	NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"Music" ofType:@"mp3"];
	if (musicPath) {
		NSURL *musicURL = [NSURL fileURLWithPath:musicPath];
		audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
		[audioPlayer setDelegate:self];
	// Get the full path of Sound12.aif
	NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound12" ofType:@"aif"];
	// If this file is actually in the bundle...
	if (soundPath) {
		// Create a URL with this path
		NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
		// Register sound file located at that URL as a system sound
		OSStatus err = AudioServicesCreateSystemSoundID((CFURLRef)soundURL, &shortSound);
		if (err != kAudioServicesNoError)
			NSLog(@"Could not load %@, error code: %d", soundURL, err);

	[[self view] addSubview:[moviePlayer view]];
	float halfHeight = [[self view] bounds].size.height / 2.0;
	float width = [[self view] bounds].size.width;
	[[moviePlayer view] setFrame:CGRectMake(0, halfHeight, width, halfHeight)];
	[moviePlayer play];

-(void)removeVideoWindow:(NSNotification *)note
	[[moviePlayer view] removeFromSuperview];

All other methods as per usual.