用AVFoundation AVPlayer循环播放视频?

yqkkidmi  于 2022-09-19  发布在  Swift
关注(0)|答案(20)|浏览(284)

在AVFoundation中有没有相对简单的循环播放视频的方法?

我已经创建了AVPlayer和AVPlayerLayer,如下所示:

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

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

然后我用以下方式播放我的视频:

[avPlayer play];

视频播放正常,但在结尾停止。对于MPMoviePlayerController,您所要做的就是将其repeatMode属性设置为正确的值。AVPlayer上似乎没有类似的特性。似乎也没有回调来告诉我电影什么时候结束,这样我就可以从头开始再放一遍。

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

rfbsl7qr

rfbsl7qr1#

对于SWIFT 3和4

NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.avPlayer?.currentItem, queue: .main) { _ in
     self.avPlayer?.seek(to: kCMTimeZero)
     self.avPlayer?.play()
}
e37o9pze

e37o9pze2#

/* "numberOfLoops" is the number of times that the sound will return to the beginning upon reaching the end. 
A value of zero means to play the sound just once.
A value of one will result in playing the sound twice, and so on..
Any negative number will loop indefinitely until stopped.

* /

@property NSInteger numberOfLoops;

此属性已在AVAudioPlayer中定义。希望这能对你有所帮助。我用的是Xcode6.3。

q1qsirdb

q1qsirdb3#

使用AVPlayerViewController下面的代码,它对我很有效

let type : String! = "mp4"
        let targetURL : String? = NSBundle.mainBundle().pathForResource("Official Apple MacBook Air Video   YouTube", ofType: "mp4")

        let videoURL = NSURL(fileURLWithPath:targetURL!)

        let player = AVPlayer(URL: videoURL)
        let playerController = AVPlayerViewController()

        playerController.player = player
        self.addChildViewController(playerController)
        self.playView.addSubview(playerController.view)
        playerController.view.frame = playView.bounds

        player.play()

所有控件都将显示,希望对您有所帮助

g6baxovj

g6baxovj4#

SWIFT 5

import UIKit
import AVKit
import AVFoundation

class VideoViewControler: UIViewController {

    // init video background and its path
    var player: AVPlayer?
    let videoURL: NSURL = Bundle.main.url(forResource: "farmer_watering", withExtension: "mp4")! as NSURL

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // begin implementing the avplayer
        player = AVPlayer(url: videoURL as URL)
        player?.actionAtItemEnd = .none
        player?.isMuted = true

        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
        playerLayer.zPosition = -1

        playerLayer.frame = view.frame

        view.layer.addSublayer(playerLayer)

        player?.play()

        // add observer to watch for video end in order to loop video
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(loopVideo),
            name: .AVPlayerItemDidPlayToEndTime,
            object: self.player?.currentItem
        )
    }

    // if video ends, will restart
    func playerItemDidReachEnd() {
        player?.seek(to: CMTime.zero)
    }

    // add this loop at the end, after viewDidLoad
    @objc func loopVideo() {
        playerItemDidReachEnd()
        player?.play()
    }
}
xn1cxnb4

xn1cxnb45#

SWIFT 4.2在Xcode 10.1中。

AVKit/AVFoundation中有一种相对简单的方法,使用AVQueuePlayer()、键值观察(KVO)技术和令牌来循环视频。

这绝对适用于一系列H.264/HEVC视频,并且对CPU的负担最小。

下面是一个代码:

import UIKit
import AVFoundation
import AVKit

class ViewController: UIViewController {

    private let player = AVQueuePlayer()
    let clips = ["01", "02", "03", "04", "05", "06", "07"]
    private var token: NSKeyValueObservation?
    var avPlayerView = AVPlayerViewController()

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)

        self.addAllVideosToPlayer()
        present(avPlayerView, animated: true, completion: { self.player.play() })
    }

    func addAllVideosToPlayer() {
        avPlayerView.player = player

        for clip in clips {
            let urlPath = Bundle.main.path(forResource: clip, ofType: "m4v")!
            let url = URL(fileURLWithPath: urlPath)
            let playerItem = AVPlayerItem(url: url)
            player.insert(playerItem, after: player.items().last)

            token = player.observe(.currentItem) { [weak self] player, _ in
                if self!.player.items().count == 1 { self?.addAllVideosToPlayer() }
            }
        }
    }
}
hof1towb

hof1towb6#

我所做的是让它循环播放,如下面的代码所示:

[player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0)
queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
    float current = CMTimeGetSeconds(time);
    float total = CMTimeGetSeconds([playerItem duration]);
    if (current >= total) {
        [[self.player currentItem] seekToTime:kCMTimeZero];
        [self.player play];
    }
}];
8fq7wneg

8fq7wneg7#

以下是SWIFT 4.1中WKWebView的主要部分WKWebView配置中的WKWebView,适用于我

wkwebView.navigationDelegate = self
wkwebView.allowsBackForwardNavigationGestures = true
self.wkwebView =  WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
let config = WKWebViewConfiguration()
config.allowsInlineMediaPlayback = true
wkwebView = WKWebView(frame: wkwebView.frame, configuration: config)
self.view.addSubview(wkwebView)
self.wkwebView.load(NSURLRequest(url: URL(string: self.getUrl())!) as URLRequest)
nkcskrwz

nkcskrwz8#

您可以添加一个AVPlayerItemDidPlayToEndTimeNotification观察器,并在选择器中从开始重放视频,代码如下

//add observer
[[NSNotificationCenter defaultCenter] addObserver:self                                                 selector:@selector(playbackFinished:)                                                     name:AVPlayerItemDidPlayToEndTimeNotification
object:_aniPlayer.currentItem];

-(void)playbackFinished:(NSNotification *)notification{
    [_aniPlayer seekToTime:CMTimeMake(0, 1)];//replay from start
    [_aniPlayer play];
}
1cklez4t

1cklez4t9#

将视频加载到AVPlayer(当然是通过其AVPlayerItem)后:

[self addDidPlayToEndTimeNotificationForPlayerItem:item];

AddDidPlayToEndTimeNotificationForPlayerItem方法:

- (void)addDidPlayToEndTimeNotificationForPlayerItem:(AVPlayerItem *)item
{
    if (_notificationToken)
        _notificationToken = nil;

    /*
     Setting actionAtItemEnd to None prevents the movie from getting paused at item end. A very simplistic, and not gapless, looped playback.
     */
    _player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
    _notificationToken = [[NSNotificationCenter defaultCenter] addObserverForName:AVPlayerItemDidPlayToEndTimeNotification object:item queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        // Simple item playback rewind.
        [[_player currentItem] seekToTime:kCMTimeZero];
    }];
}

在您的view WillDis现方法中:

if (_notificationToken) {
        [[NSNotificationCenter defaultCenter] removeObserver:_notificationToken name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
        _notificationToken = nil;
    }

在实现文件内的视图控制器的接口声明中:

id _notificationToken;

在你尝试之前,需要先看看它的启动和运行情况吗?下载并运行此示例应用程序:

Https://developer.apple.com/library/prerelease/ios/samplecode/AVBasicVideoOutput/Listings/AVBasicVideoOutput_APLViewController_m.html#//apple_ref/doc/uid/DTS40013109-AVBasicVideoOutput_APLViewController_m-DontLinkElementID_8

在我的应用程序中,它使用的正是这段代码,在视频的结尾和开头之间没有任何停顿。事实上,根据视频的不同,除了时间码显示之外,我无法判断视频是从头开始的。

9gm1akwq

9gm1akwq10#

我在答案中找不到我的解决方案。观察指定给资产期限的边界时间可能会很有帮助。当观察者被触发时,寻求开始并重播。

player?.addBoundaryTimeObserver(forTimes: [NSValue(time: asset.duration)], queue: .main) { [weak self] in
    self?.player?.seek(to: .zero, completionHandler: { [weak self] _ in
        self?.player?.play()
    })
}
sshcrbum

sshcrbum11#

当玩家结束时,你可以得到一个通知。检查AVPlayerItemDidPlayToEndTimeNotification

设置播放器时:

Objc

avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; 

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

这将防止玩家在结束时停顿。

在通知中:

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

这将使电影倒带。

别忘了在释放玩家的时候取消注册通知。

SWIFT

avPlayer?.actionAtItemEnd = .none

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

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

SWIFT 4+

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

zqdjd7g912#

我在Objective中的解决方案--使用AVQueuePlayerc--似乎必须复制AVPlayerItem,并在完成第一个元素的回放后立即添加另一个副本。“有点”说得通,而且对我来说没有任何问题。

NSURL *videoLoopUrl; 
// as [[NSBundle mainBundle] URLForResource:@"assets/yourVideo" withExtension:@"mp4"]];
AVQueuePlayer *_loopVideoPlayer;

+(void) nextVideoInstance:(NSNotification*)notif
{
 AVPlayerItem *currItem = [AVPlayerItem playerItemWithURL: videoLoopUrl];

[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(nextVideoInstance:)
                                      name:AVPlayerItemDidPlayToEndTimeNotification
                                      object: currItem];

 [_loopVideoPlayer insertItem:currItem afterItem:nil];
 [_loopVideoPlayer advanceToNextItem];

}

+(void) initVideoPlayer {
 videoCopy1 = [AVPlayerItem playerItemWithURL: videoLoopUrl];
 videoCopy2 = [AVPlayerItem playerItemWithURL: videoLoopUrl];
 NSArray <AVPlayerItem *> *dummyArray = [NSArray arrayWithObjects: videoCopy1, videoCopy2, nil];
 _loopVideoPlayer = [AVQueuePlayer queuePlayerWithItems: dummyArray];

 [[NSNotificationCenter defaultCenter] addObserver: self
                                      selector: @selector(nextVideoInstance:)
                                      name: AVPlayerItemDidPlayToEndTimeNotification
                                      object: videoCopy1];

 [[NSNotificationCenter defaultCenter] addObserver: self
                                      selector: @selector(nextVideoInstance:)
                                      name: AVPlayerItemDidPlayToEndTimeNotification
                                      object: videoCopy2];
}

https://gist.github.com/neonm3/06c3b5c911fdd3ca7c7800dccf7202ad

ej83mcc0

ej83mcc013#

这对我来说很有效,没有打嗝的问题,要点是在调用earkToTime方法之前暂停播放器

1.初始化AVPlayer

let url = NSBundle.mainBundle().URLForResource("loop", withExtension: "mp4")
let playerItem = AVPlayerItem(URL: url!)

self.backgroundPlayer = AVPlayer(playerItem: playerItem)
let playerLayer = AVPlayerLayer(player: self.backgroundPlayer)

playerLayer.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height)
self.layer.addSublayer(playerLayer)
self.backgroundPlayer!.actionAtItemEnd = .None
self.backgroundPlayer!.play()

1.登记通知

NSNotificationCenter.defaultCenter().addObserver(self, selector: "videoLoop", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.backgroundPlayer!.currentItem)

1.Video oLoop函数

func videoLoop() {
  self.backgroundPlayer?.pause()
  self.backgroundPlayer?.currentItem?.seekToTime(kCMTimeZero)
  self.backgroundPlayer?.play()
}
0pizxfdo

0pizxfdo14#

SWIFT 5:

private var player: AVPlayer?

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(restartVideo),
                                           name: .AVPlayerItemDidPlayToEndTime,
                                           object: self.player?.currentItem)
}

@objc func restartVideo() {
    player?.pause()
    player?.currentItem?.seek(to: CMTime.zero, completionHandler: { _ in
        self.player?.play()
    })
}
r8xiu3jd

r8xiu3jd15#

为了避免视频倒带时的间隙,在一个构图中使用同一资源的多个副本对我来说效果很好。我在这里找到了它:www.developers-life.com/avplayer-looping-video-without-hiccupdelays.html(链接现已失效)。

AVURLAsset *tAsset = [AVURLAsset assetWithURL:tURL];
CMTimeRange tEditRange = CMTimeRangeMake(CMTimeMake(0, 1), CMTimeMake(tAsset.duration.value, tAsset.duration.timescale));
AVMutableComposition *tComposition = [[[AVMutableComposition alloc] init] autorelease];
for (int i = 0; i < 100; i++) { // Insert some copies.
    [tComposition insertTimeRange:tEditRange ofAsset:tAsset atTime:tComposition.duration error:nil];
}
AVPlayerItem *tAVPlayerItem = [[AVPlayerItem alloc] initWithAsset:tComposition];
AVPlayer *tAVPlayer = [[AVPlayer alloc] initWithPlayerItem:tAVPlayerItem];

相关问题