如何在屏幕变暗和锁定时保持音频播放?

How to keep audio playing when screen dims and locks?

我的 Xamarin.iOS 应用程序中嵌入了一个广播播放器,但是当屏幕锁定时,音频停止播放。根据此线程 https://forums.xamarin.com/discussion/36651/play-audio-in-background-for-iphone,我尝试将其添加到我的 AppDelegate 的 FinishedLaunching 方法中,但它不起作用:

var currentSession = AVAudioSession.SharedInstance(); currentSession.SetCategory(AVAudioSessionCategory.Playback, AVAudioSessionCategoryOptions.MixWithOthers); currentSession.SetActive(true);

即使 phone 处于静音模式,

AVAudioSessionCategory.Playback 也会播放音频。 (这有效)。 AVAudioSessionCategoryOptions.MixWithOthers 允许从多个应用程序同时播放多个声音。 (我没有测试过这个,但它与我的问题无关)。

currentSession.SetActive(true) 应该允许在屏幕锁定时在后台播放音频,但它不起作用。

有什么想法吗?

您需要为您的应用注册背景音频。参见:https://docs.microsoft.com/en-us/xamarin/ios/app-fundamentals/backgrounding/ios-backgrounding-techniques/registering-applications-to-run-in-background

Applications can be registered by setting the Required Background Modes property in the application's Info.plist. An application can register in as many categories as it requires

因此,打开您的 Info.plist 文件并 select 以下选项:

对战(PC):

VS (Mac):