user2498312
user2498312

Reputation: 11

Beginning graphics...adding AVPlayerLayer to NSView

I saw a similar question to the one I am asking about how to add a AVPlayerLayer to an NS View but I can't see there full source code to understand how it works. The heart of my question is I create a player object and initialize it with a move NSURL. I create an AVPlayerLayer object and initialize it with the player. When I try to add the AVPlayerLayer to myself (i am NSView) and run the program I don't get anything.

NSURL *movie = [[NSURL alloc]     initWithString:@"file://localhost/Users/matthewmichal/Desktop/A%20Good%20To%20Die%20Hard.mov"];
[player initWithURL:movie];
[self setWantsLayer:YES];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
[self.layer addSublayer:playerLayer];
    [player play];

Upvotes: 1

Views: 628

Answers (2)

r farnell
r farnell

Reputation: 71

Import AVFoundation

#import <AVFoundation/AVFoundation.h> 

Create the AVPlayer object and the player layer (I define these in the header)

AVPlayer *avPlayer;
AVPlayerLayer* playerLayer;

Tell the NSView you want to use layers, assuming your class in an NSView

[self setWantsLayer:YES];

Now the function...

[avPlayer pause];
avPlayer = nil;
playerLayer = nil;

NSURL *videoURL = [NSURL fileURLWithPath:@"file://localhost/Users/matthewmichal/Desktop/A%20Good%20To%20Die%20Hard.mov"];
avPlayer = [AVPlayer playerWithURL:videoURL];
playerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
playerLayer.frame = self.frame;//or your desired CGRect
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
//playerLayer.masksToBounds = YES;
[self.layer addSublayer:playerLayer];

[avPlayer play];

Upvotes: 0

mattnunes
mattnunes

Reputation: 69

You should probably consider reading the AVFoundation guide from Apple:

https://developer.apple.com/library/ios/DOCUMENTATION/AudioVideo/Conceptual/AVFoundationPG/Articles/00_Introduction.html

It doesn't specifically go into what the minor differences are between AppKit and UIKit, but you've already got it ([NSView setWantsLayer:], [NSView addSublayer]). What you are not doing correctly is registering to observe updates to the AVPlayer's status property:

As with AVAsset, though, simply initializing a player item doesn’t necessarily mean it’s ready for immediate playback. You can observe (using key-value observing) an item’s status property to determine if and when it’s ready to play.

Assuming all other things are correct (which is hard to tell from your code - for example, are you sure the NSURL is being formed properly?), that's most likely what's wrong - you're adding the layer to the NSView before the player is ready to play. If not, then I'd make sure that your NSURL is actually pointing at the resource you're looking for.

Upvotes: 2

Related Questions