我一直在为几个 iOS 应用程序使用 AVAudioPlayer,它们在屏幕锁定后都成功播放,直到我的 iPad2 上的 iOS6(或 iOS5),现在它们停止了。这是我设置它的方法,它曾经可以正常工作:
// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];
// Use this code instead to allow the app sound to continue to play when the screen is locked.
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 0;
AudioSessionSetProperty ( kAudioSessionProperty_OverrideCategoryMixWithOthers,
sizeof (doSetProperty),
&doSetProperty
);
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
// Registers the audio route change listener callback function
AudioSessionAddPropertyListener (
kAudioSessionProperty_AudioRouteChange,
audioRouteChangeListenerCallback,
(__bridge void *)self
);
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
// Instantiates the AVAudioPlayer object, initializing it with the sound
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: medURL error: nil];
self.appSoundPlayer = newPlayer;
// "Preparing to play" attaches to the audio hardware and ensures that playback
// starts quickly when the user taps Play
[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume: 0.5];
[appSoundPlayer setDelegate: self];
请注意,我将类别设置为 AVAudioSessionCategoryPlayback,这是之前推荐的修复。自从我升级到 iOS6 后,这不起作用——事实证明,这在 iOS5 上也不起作用!
更新:我找到了一个似乎基于这篇文章的答案:AVAudioPlayer 停止在屏幕锁定时播放,即使类别是 AVAudioSessionCategoryPlayback
基本上我进入目标的信息页面并添加了一个新键“必需的背景模式”,为此我添加了一个字符串类型值“应用程序播放音频”。现在它在完全关闭屏幕之前一直穿过轨道。