无缝循环视频

Seamless Loop Video

我在 iOS 中看到了很多无缝循环播放视频的示例,但我还没有找到太多可以在 MacOS 中使用的示例。我只是在试验 AVPlayer 在 window 中循环播放视频。我可以让视频播放和循环播放,但我无法让它无缝播放。

我这里有一个循环播放 3 秒视频的示例,您可以清楚地看到它不是无缝循环。

我知道有一个 AVPlayerLooper,但我是新手,不知道如何实现它。

#import "AppDelegate.h"
#import "VideoWindow1.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>

@interface AppDelegate ()

@property (weak) IBOutlet AVPlayerView *playerView;
@property (weak) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSWindow *VideoWindow;

@end

@implementation AppDelegate

AVPlayer *player;
BOOL loopPlayer;

- (void) movieEndDetected:(NSNotification *) note
{
    if (loopPlayer) {
        [player seekToTime:kCMTimeZero];
        [player play];
    }
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    loopPlayer = YES;

    // set up player
    NSBundle *mb = [NSBundle mainBundle];
    NSURL *demoURL = [mb URLForResource:@"Video2" withExtension:@"mp4"];
    player = [[AVPlayer alloc] initWithURL:demoURL];
    self.playerView.player = player;
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self selector:@selector(movieEndDetected:)
               name:@"AVPlayerItemDidPlayToEndTimeNotification"
             object:player.currentItem];
            [player play];
    [_VideoWindow setAspectRatio:NSMakeSize(16, 9)];
}

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

@end

我能够使用 avlooper 实现无缝循环。

#import "VideoWindow.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>

@interface VideoWindow ()

@property (strong) IBOutlet AVPlayerView *playerView;
@property (strong) IBOutlet NSWindow *aspectView;

@end

@implementation VideoWindow

{
    AVPlayerItem *_playerItem;
    AVQueuePlayer *_player;
    AVPlayerLooper *_playerLooper;
    AVPlayerLayer *_playerLayer;
}


- (void)windowDidLoad {
    [super windowDidLoad];
    NSString *videoFile = [[NSBundle mainBundle] pathForResource:@"Video2" ofType:@"mp4"];
    NSURL *videoURL = [NSURL fileURLWithPath:videoFile];
    _playerItem = [AVPlayerItem playerItemWithURL:videoURL];
    _player = [AVQueuePlayer queuePlayerWithItems:@[_playerItem]];
    _playerLooper = [AVPlayerLooper playerLooperWithPlayer:_player templateItem:_playerItem];
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.frame = self.playerView.bounds;
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.playerView.layer addSublayer:_playerLayer];
    [_aspectView setAspectRatio:NSMakeSize(16, 9)];
    [_player play];
}



- (void)windowWillClose:(NSNotification *)aNotification {
    [_player pause];
    [_player seekToTime:kCMTimeZero];
}

@end