【问题标题】:Detect AVPlayerItem Status change检测 AVPlayerItem 状态变化
【发布时间】:2019-09-05 18:06:56
【问题描述】:

这是我的 (Xamarin C#) 代码:(playerAVPlayer。)

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

即使播放器玩得很好,它也从不调用ReadyNow(NSNotification obj)

如何修复它以调用该方法? (我不知道错误是在 Xamarin/C# 部分还是在我正在使用的对象等中。如果用 Swift 编写,这将是相同的错误。)

【问题讨论】:

    标签: c# ios swift xamarin xamarin.ios


    【解决方案1】:

    您可以获取玩家的当前项目并将观察者添加到其中。

    属性:

    private AVPlayerItem CurrentItem => Player.CurrentItem;
    

    观察者:

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

    如果你愿意,也可以附上loadedTimeRanges

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

    注意:始终确保在附加之前分离观察者的状态:

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

    编辑:StatusObservationContext 只是一个属性,指向status 字符串。

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

    有用的资源 您可以在 Martinj 的优秀软件包 - XamarinMediaManager 中找到您的 AVPlayer 实现可能需要的一切。

    来源:

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

    【讨论】:

    • 谢谢。 Always be sure to detach the observer for the status to an item without one! - 我不明白那句话。
    • 另外,我没有StatusObservationContext
    • 我使用它有点不同,但 CurrentItem.AddObserver 是引导我走上正确道路的原因。谢谢!
    • 顺便说一句,我也赞成您的答案(以及其他答案),但看起来有人反对这两个答案。它们现在都为 0,但细分显示两个答案均为 +1(我的)和 -1。
    【解决方案2】:

    您正在尝试观察单个AVPlayerItem 实例当前保存在CurrentItem 属性中,即使它当前为空。

    您可以在AVPlayer 实例上观察并使用NSObjectkeyPath 您希望观察其变化:

    示例:

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

    注意:持有一个参考。到返回的IDisposable 否则你的观察者可能会超出范围并且|或者你会泄漏内存。

    【讨论】:

    • 谢谢。我现在正在检查。但是你说的最后一段是什么意思?你指的是obs吗?我想我可以忽略它,让它得到 GCd。如果不是 - 我真的很高兴我问了这个问题!
    • @ispiro 可观察到的 IDisposable 持有一个幼稚的 ref,GC'ing 不会调用 dispose:stackoverflow.com/questions/1691846/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 2015-12-12
    • 2019-10-05
    • 1970-01-01
    相关资源
    最近更新 更多