如何将AVPlayer添加到QWidget?

时间:2013-06-26 18:41:56

标签: macos cocoa qt4 avplayer qt4.8

在Mac上,我想使用AVPlayer在我的Qt 4.8应用程序中播放视频,因为它具有Phonon::VideoPlayer没有的功能。

如何将AVPlayerLayer添加到QWidget,以便它变得可见?我正在做以下事情:

    pimpl->player = [[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:videoFile]];
    pimpl->player.actionAtItemEnd = AVPlayerActionAtItemEndPause;
    pimpl->player.rate = 0;

    pimpl->playerLayer = [[AVPlayerLayer playerLayerWithPlayer:pimpl->player] retain];
    [pimpl->playerLayer setFrame: CGRectMake(0, 0, rect().width(), rect().height())];

    NSView* view = (NSView*)winId();
    [[view layer] addSublayer:pimpl->playerLayer];

当我播放视频时,我听到了,但我看不到它。知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

使用QMacCocoaViewContainer,而不是使用winId(),但QMacCocoaViewContainer有一个错误,除非setAttribute(Qt :: WA_NativeWindow),否则将导致NSView不显示在Qt 4.8中;已设定。

同样,NSView可能没有图层,因此需要创建图层。

    [pimpl->view setWantsLayer:YES];
    [pimpl->view makeBackingLayer];

总的来说,它看起来像:

    pimpl->view = [[NSView alloc] initWithFrame: CGRectMake(0, 0, w, h)];
    [pimpl->view setHidden:NO];
    [pimpl->view setNeedsDisplay:YES];
    [pimpl->view setWantsLayer:YES];
    [pimpl->view makeBackingLayer];

    viewFrame = new QMacCocoaViewContainer(NULL, this);
    viewFrame->setGeometry(rect());
    viewFrame->setVisible(true);
    viewFrame->setCocoaView(pimpl->view);

    NSString* videoFile = [NSString stringWithCString:filename.toUtf8().data() encoding:NSUTF8StringEncoding];

    pimpl->player = [[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:videoFile]];
    pimpl->player.actionAtItemEnd = AVPlayerActionAtItemEndPause;
    pimpl->player.rate = 0;

    pimpl->playerLayer = [[AVPlayerLayer playerLayerWithPlayer:pimpl->player] retain];
    [pimpl->playerLayer setFrame: CGRectMake(0, 0, w, h)];
    [pimpl->playerLayer setHidden: NO];

    CALayer* layer = [pimpl->view layer];
    [layer addSublayer:pimpl->playerLayer];