【发布时间】:2020-12-11 08:08:34
【问题描述】:
我创建了一个嵌入了 AVPlayer 的自定义 NSView,但它根本没有显示
这是我的标题:
@interface VideoPlayer : NSView
- (void)loadVideo;
@end
实施:
@implementation VideoPlayer
AVPlayer *avPlayer;
AVPlayerLayer* playerLayer;
- (instancetype)initWithFrame:(NSRect)rect {
self = [super initWithFrame:rect];
[self setWantsLayer:YES];
[self setNeedsDisplay:YES];
self.hidden = NO;
return self;
}
-(void) loadVideo {
[avPlayer pause];
avPlayer = nil;
playerLayer = nil;
NSURL *videoURL = [NSURL fileURLWithPath:@"file://~/Documents/tests.mp4"];
//same error with a valid url
//NSURL *videoURL = [NSURL URLWithString:@"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4"];
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];
}
@end
这就是我创建视图的方式:
view = [[VideoPlayer alloc] initWithFrame:NSMakeRect(0, 0, 500, 500)];
view.hidden = false;
[view loadVideo];
[parent_view addSubview:view];
我尝试了多种组合,但结果始终相同...应用程序上没有呈现任何内容。
另一方面,如果我像这样覆盖视图中的 drawRect 方法:
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
[[NSColor whiteColor] setFill];
NSRectFill(dirtyRect);
[super drawRect:dirtyRect];
}
我得到一个白色矩形,它应该显示我的视频,这是预期的。所以我假设我遗漏了其他东西,但大多数示例都使用 UIView 这不是我目前的选择(我正在处理一些特定的约束)
有什么想法吗?
谢谢
更新:
这终于对我有用了:
-(void) loadVideo {
AVPlayer *avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:@"file://localhost/Users/xxxxxxxx/Documents/xxxxxxx.mp4"]];
AVPlayerView *playerView = [[AVPlayerView alloc] initWithFrame:self.bounds];
[playerView setPlayer:avPlayer];
[self addSubview:playerView];
[playerView.player play];
}
【问题讨论】:
-
我正在使用 ~/Documents/tests.mp4 中的文件。如果网址无效,不应该至少显示一个空播放器吗?
-
尝试使用 NSURL *videoURL = [NSURL URLWithString:@"commondatastorage.googleapis.com/gtv-videos-bucket/sample/…; 但它仍然没有显示任何内容。(* 正在修剪 url 的 http 部分)
-
也许你应该在
addSubView之后loadVideo。检查loadVideo中是否存在 view.window。 View 只是一个委托。没有窗口它什么也做不了。 -
试过了,self.window 存在。 addSubView 之后的 loadVideo 也没有解决问题。到目前为止,使其工作的唯一方法是覆盖 drawRect
标签: objective-c macos avplayer nsview avkit