You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xamarin.iOS中通过代码控制MPNowPlayingInfoCenter的播放/暂停按钮

解决Xamarin.iOS中Now Playing控制中心播放/暂停按钮状态不更新的问题

针对你遇到的设置PlaybackRate后控制中心按钮状态无变化的问题,以下是几个经过验证的解决办法:


1. 必须注册并处理远程控制事件

iOS要求音频类APP主动注册远程控制事件,否则系统不会同步控制中心的状态。

在AppDelegate的FinishedLaunching方法中添加注册代码:

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    // 注册远程控制事件
    UIApplication.SharedApplication.BeginReceivingRemoteControlEvents();
    
    // 设置音频会话为播放模式(必须步骤)
    var audioSession = AVAudioSession.SharedInstance();
    NSError error = null;
    audioSession.SetCategory(AVAudioSessionCategory.Playback, out error);
    if (error != null)
    {
        Console.WriteLine($"音频会话设置失败: {error.LocalizedDescription}");
    }
    audioSession.SetActive(true, out error);
    
    return base.FinishedLaunching(app, options);
}

同时在负责播放的页面/ViewController中重写RemoteControlReceived方法(即使仅做基础实现,也能让系统识别APP支持远程控制):

public override void RemoteControlReceived(UIApplication application, UIEvent evt)
{
    base.RemoteControlReceived(application, evt);
    // 这里可处理控制中心传来的播放/暂停指令
    if (evt.Subtype == UIEventSubtype.RemoteControlPlay)
    {
        // 执行播放逻辑
    }
    else if (evt.Subtype == UIEventSubtype.RemoteControlPause)
    {
        // 执行暂停逻辑
    }
}

2. 每次更新时创建新的MPNowPlayingInfo实例

不要复用同一个MPNowPlayingInfo对象,Xamarin的绑定可能存在引用缓存问题,创建新实例可确保系统检测到状态变化:

修改播放状态更新代码为:

// 基于原有信息创建新实例
var newNowPlayingInfo = new MPNowPlayingInfo
{
    Artist = _nowPlayingInfo.Artist,
    Title = _nowPlayingInfo.Title,
    PlaybackDuration = _nowPlayingInfo.PlaybackDuration,
    ElapsedPlaybackTime = _nowPlayingInfo.ElapsedPlaybackTime,
    Artwork = _nowPlayingInfo.Artwork,
    PlaybackRate = isPlaying ? 1.0d : 0.0d
};

// 更新控制中心
MPNowPlayingInfoCenter.DefaultCenter.NowPlaying = newNowPlayingInfo;
// 更新本地引用
_nowPlayingInfo = newNowPlayingInfo;

3. 强制触发控制中心刷新

如果上述方法无效,可尝试通过重新注册远程控制事件强制刷新:

// 先停止接收远程控制事件
UIApplication.SharedApplication.EndReceivingRemoteControlEvents();
// 重新注册
UIApplication.SharedApplication.BeginReceivingRemoteControlEvents();

// 再次同步NowPlaying信息
MPNowPlayingInfoCenter.DefaultCenter.NowPlaying = _nowPlayingInfo;

额外检查点

  • 确认Xamarin.iOS版本(16.1.1.27)与测试设备iOS版本(16.3.1)的兼容性,部分跨版本绑定可能存在bug,可尝试升级Xamarin.iOS至对应iOS版本的兼容包。
  • 确保设置PlaybackRate时,APP内音频的实际播放状态与设置值完全一致,状态不一致会导致系统拒绝更新控制中心UI。

内容的提问来源于stack exchange,提问作者Mark Reynolds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:22:55