用AVFoundation AVPlayer循环播放视频? [英] Looping a video with AVFoundation AVPlayer?

查看:400
本文介绍了用AVFoundation AVPlayer循环播放视频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在AVFoundation中有一种相对简单的循环视频方式吗?

Is there a relatively easy way of looping a video in AVFoundation?

我已经创建了我的AVPlayer和AVPlayerLayer:

I've created my AVPlayer and AVPlayerLayer like so:

avPlayer = [[AVPlayer playerWithURL:videoUrl] retain];
avPlayerLayer = [[AVPlayerLayer playerLayerWithPlayer:avPlayer] retain];

avPlayerLayer.frame = contentView.layer.bounds;
[contentView.layer addSublayer: avPlayerLayer];

然后我播放我的视频:

[avPlayer play];

视频播放正常,但最后会停止播放。使用MPMoviePlayerController,您只需将其 repeatMode 属性设置为正确的值。 AVPlayer上似乎没有类似的属性。电影完成时似乎也没有回调告诉我,所以我可以寻找开头并再次播放。

The video plays fine but stops at the end. With the MPMoviePlayerController all you have to do is set its repeatMode property to the right value. There doesn't appear to be a similar property on AVPlayer. There also doesn't seem to be a callback that will tell me when the movie has finished so I can seek to the beginning and play it again.

我不是使用MPMoviePlayerController因为它有一些严重的限制。我希望能够一次播放多个视频流。

I'm not using MPMoviePlayerController because it has some serious limitations. I want to be able to play back multiple video streams at once.

推荐答案

您可以在播放器结束时收到通知。检查 AVPlayerItemDidPlayToEndTimeNotification

You can get a Notification when the player ends. Check AVPlayerItemDidPlayToEndTimeNotification

设置播放器时:

ObjC

  avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; 

  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(playerItemDidReachEnd:)
                                               name:AVPlayerItemDidPlayToEndTimeNotification
                                             object:[avPlayer currentItem]];

这会阻止玩家在结束时暂停。

this will prevent the player to pause at the end.

- (void)playerItemDidReachEnd:(NSNotification *)notification {
    AVPlayerItem *p = [notification object];
    [p seekToTime:kCMTimeZero];
}

这将回放电影。

不要忘记在发布播放器时取消注册通知。

Don't forget un unregister the notification when releasing the player.

Swift

NotificationCenter.default.addObserver(self,
                                       selector: #selector(playerItemDidReachEnd(notification:)),
                                       name: Notification.Name.AVPlayerItemDidPlayToEndTime,
                                       object: avPlayer?.currentItem)

 @objc func playerItemDidReachEnd(notification: Notification) {
        if let playerItem: AVPlayerItem = notification.object as? AVPlayerItem {
            playerItem.seek(to: kCMTimeZero, completionHandler: nil)
        }
    }

这篇关于用AVFoundation AVPlayer循环播放视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆