Search code examples
objective-cmacosvideoxcode5.1

Playing a video in OSX


I'm developing a mac app that requires to play tutorial videos in the app itself. when a user presses a button on the app it should play the video here's the code for xcode 4.3 (incompatible with xcode 5.1)

@synthesize movieView;
-(IBAction)playVideo:(id)sender {
NSString *videoPath = [[NSBundle mainBundle] pathForResource:"video name" ofType:@"mp4";
NSURL *videoURL = [NSURL fileURLWithPath: videoPath];
NSError *error = nil;

NSDictionary *attrib = [NSDictionary dictionaryWithObjectsAndKeys:
                       [NSNumber  numberWithBool:YES],
                        QTMovieOpenForPlaybackAttribute,
                        videoURL, QTMovieURLAttribute,
                        [NSNumber numberWithBool:YES],
                        QTMovieOpenAsyncRequiredAttribute, nil];
QTMovie *newMovie = [[QTMovie alloc] initWithAttributes: attrib error: &error];
[movieView setMovie:newMovie];
[movieView play:newMovie];

}

I'm using xcode 5.1 for osx 10.8


Solution

  • Apple started a transition from QuickTime APIs (including QTKit) to AVFoundation beginning with OS X 10.7. There is a detailed technical note about that transition.

    The easiest way to play a video in a modern Mac app is via AVKit (available since 10.9).
    To get a basic view that displays a video bundled with your app you have to:

    1. Add AVKit & AVFoundation to the "Linked Frameworks and Libraries" section of your project
    2. Drag an AVPlayerView to a window in Interface Builder
    3. Connect an Outlet to the player view in one of your controllers
    4. Instantiate an AVPlayer that loads the video resource from your bundle

    This is the code to load your asset:

    NSURL* videoURL = [[NSBundle mainBundle] URLForResource:@"video name" withExtension:@"mp4"];
    self.playerView.player = [AVPlayer playerWithURL:videoURL];