3

How does one loop a video using AVPlayer under Xamarin iOS? ObjectiveC solution suggests the use of an observable notification. It's not clear how to do this with C# syntax or the Xamarin API of the AVPlayer.

You can see the ObjectiveC question and answer here: Looping a video with AVFoundation AVPlayer?

Community
  • 1
  • 1
astone26
  • 1,222
  • 11
  • 16

2 Answers2

6

Sorry, @Pandalink, we should have updated an answer here once we figured it out...

We found something rather quite simple:

NSNotificationCenter.DefaultCenter.AddObserver (AVPlayerItem.DidPlayToEndTimeNotification, (notify) => {
            player.Seek(CoreMedia.CMTime.Zero);
            notify.Dispose ();
        });
astone26
  • 1,222
  • 11
  • 16
4

This worked for me:

AVAsset videoAsset;
AVPlayerItem videoPlayerItem;
AVPlayer videoPlayer;
AVPlayerLayer videoPlayerLayer;
NSObject videoEndNotificationToken;

public override void ViewDidLoad()
{
    videoAsset = AVAsset.FromUrl(NSUrl.FromFilename("video.mp4"));
    videoPlayerItem = new AVPlayerItem(videoAsset);
    videoPlayer = new AVPlayer(videoPlayerItem);
    videoPlayerLayer = AVPlayerLayer.FromPlayer(videoPlayer);
    videoPlayerLayer.Frame = View.Frame;
    View.Layer.AddSublayer(videoPlayerLayer);
    videoPlayer.Play();

    // Subscribe to video end notification
    videoPlayer.ActionAtItemEnd = AVPlayerActionAtItemEnd.None;
    videoEndNotificationToken = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, VideoDidFinishPlaying, videoPlayerItem);
}

private void VideoDidFinishPlaying(NSNotification obj)
{
    Console.WriteLine("Video Finished, will now restart");
    videoPlayer.Seek(new CMTime(0, 1));
}
Alex West
  • 780
  • 4
  • 14