Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Cocoa 开始图形…将AVPlayerLayer添加到NSView_Cocoa - Fatal编程技术网

Cocoa 开始图形…将AVPlayerLayer添加到NSView

Cocoa 开始图形…将AVPlayerLayer添加到NSView,cocoa,Cocoa,我看到了一个类似的问题,关于如何将AVPlayerLayer添加到NS视图,但我没有看到完整的源代码来理解它是如何工作的。我的问题的核心是我创建一个玩家对象,并用移动NSURL初始化它。我创建了一个AVPlayerLayer对象并用播放器初始化它。当我尝试将AVPlayerLayer添加到我自己(我是NSView)并运行该程序时,我什么都没有得到 NSURL *movie = [[NSURL alloc] initWithString:@"file://localhost/Users/m

我看到了一个类似的问题,关于如何将AVPlayerLayer添加到NS视图,但我没有看到完整的源代码来理解它是如何工作的。我的问题的核心是我创建一个玩家对象,并用移动NSURL初始化它。我创建了一个AVPlayerLayer对象并用播放器初始化它。当我尝试将AVPlayerLayer添加到我自己(我是NSView)并运行该程序时,我什么都没有得到

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];

你可能应该考虑阅读Apple指南:

它没有具体讨论AppKit和UIKit之间的细微差别,但您已经了解了(
[NSView setWantsLayer:
[NSView addSublayer]
)。您未正确执行的操作是注册以观察AVPlayer状态属性的更新:

不过,与AVAsset一样,简单地初始化播放器项目并不一定意味着它可以立即播放。您可以观察(使用键值观察)项目的状态属性,以确定它是否以及何时准备好播放

假设所有其他事情都是正确的(这很难从您的代码中分辨出来-例如,您确定NSURL的格式正确吗?),这很可能是错误的-您在玩家准备玩之前将层添加到NSView。如果没有,那么我会确保您的NSURL实际上指向您正在寻找的资源。

Import AVFoundation

#import <AVFoundation/AVFoundation.h> 
假设您的类位于NSView中,告诉NSView您要使用层

[self setWantsLayer:YES];
现在函数

[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];
[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];