Search code examples
objective-cmacoscocoaavplayeravplayerlayer

AVPlayer plays sound but view is not shown in mac application


I'd like to play local movie in AVPlayer on macintosh app. I've created simple code but movie doesn't want to show played movie. It plays sound of the movie but there is no view visible. What am I missing?

It's my first playing simple app.

My code:

@implementation MasterViewController

    - (void)viewDidLoad {
    [super viewDidLoad];

    NSView *containerView = [[NSView alloc] initWithFrame:CGRectMake(0.0f, 0, 390.0f, 400.0f)];


NSString *videoPath = [[NSBundle mainBundle] pathForResource: @"Fatality.mp4" ofType:nil];
NSLog(@"%@", videoPath);



NSURL *fileURL = [NSURL fileURLWithPath:videoPath];
self.player = [AVPlayer playerWithURL:fileURL];
AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.player.actionAtItemEnd = AVPlayerActionAtItemEndNone;

layer.frame = CGRectMake(0, 0, 1024, 768);
[self.view.layer addSublayer: layer];

[self.player play];

}

@end

And AppDelegate:

@interface AppDelegate ()

@property (weak) IBOutlet NSWindow *window;
@property (nonatomic,strong) IBOutlet MasterViewController *masterViewController;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application

    self.masterViewController = [[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil];

    // 2. Add the view controller to the Window's content view
    [self.window.contentView addSubview:self.masterViewController.view];
    self.masterViewController.view.frame = ((NSView*)self.window.contentView).bounds;


}

- (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application
}

@end

Solution

  • You have to add your containerView as a subview of the master view controllers view

    [self.view addSubView:containerView];
    

    A trick I often do while debugging is to set the background colour of a view I am interested in to something bright (red, yellow, cyan....) and then make sure that the view shows up where I expect it to be.