ispiro
ispiro

Reputation: 27703

Detect AVPlayerItem Status change

This is my (Xamarin C#) code: (player is an AVPlayer.)

var v = NSNotificationCenter.DefaultCenter.AddObserver(new NSString("Status"), ReadyNow, player.CurrentItem);

It never calls ReadyNow(NSNotification obj) even though the player plays fine.

How do I fix it to call the method? (I don't know if the error is in the Xamarin/C# part or in the object I'm using etc. which would be the same error if written in Swift.)

Upvotes: 1

Views: 552

Answers (2)

Mihail Duchev
Mihail Duchev

Reputation: 4821

You can get the player's current item and add the observer to it.

The property:

private AVPlayerItem CurrentItem => Player.CurrentItem;

The observer:

CurrentItem.AddObserver(this, new NSString("status"), 
    NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial,
    StatusObservationContext.Handle);

If you want, you can also attach loadedTimeRanges:

CurrentItem.AddObserver(this, new NSString("loadedTimeRanges"), 
    NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New,
    LoadedTimeRangesObservationContext.Handle);

NB: Always be sure to detach the observer for the status before attaching:

CurrentItem.RemoveObserver(this, new NSString("status"));

Edit: StatusObservationContext is simply a property, pointing to status string.

public static readonly NSString StatusObservationContext = new NSString("Status");

Useful resources You can find everything that you may need for your AVPlayer implementation in Martinj's excellent package - XamarinMediaManager.

Sources:

  1. Play Audio and Video with the MediaManager Plugin for Xamarin
  2. Plugin.MediaManager NuGet
  3. GitHub

Upvotes: 1

SushiHangover
SushiHangover

Reputation: 74174

You are trying to observe on the single AVPlayerItem instance is currently held in the CurrentItem property, even if it is currently null.

You can observe on the AVPlayer instance and use the keyPath of the NSObject that you wish to observe changes on:

Example:

obs = player.AddObserver("currentItem", NSKeyValueObservingOptions.New, (NSObservedChange obj) =>
{
    Console.WriteLine($"{obj.NewValue}");
});

Note: Hold a ref. to the returned IDisposable otherwise your observer can go out of scope and|or you will leak mem.

Upvotes: 0

Related Questions