设备被locking时,AVAudioPlayer不会播放
我在我的应用程序中使用AVAudioPlayer
。 当我select一首正在播放的歌曲时,但是我的问题是,当设备被locking时,它不会播放。
您需要阅读Apple的文档中的后台执行代码 。 如果您将App的Info.plist
的UIBackgroundModes
键设置为audio
,audio将在后台继续播放。
请参阅上述文档中声明您支持和播放背景audio 的背景任务部分。
我们需要用AVAudioPlayer通过两步来使音乐在后台播放:
步骤1:select项目 – >function – >启用背景模式 – >selectaudio模式
第2步:使用此代码:
NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"demo" withExtension:@"mp3"]; avSound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil]; [avSound setDelegate:self]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil]; [[AVAudioSession sharedInstance] setActive: YES error: nil]; [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [avSound prepareToPlay]; [avSound setNumberOfLoops:-1]; [avSound setVolume:1.0];
请注意,即使应用程序位于后台,也可以使用此行开始播放音乐:
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
据我所知,设备locking时不能播放声音。 难道你不能只是禁止设备locking和活着的应用程序一直活跃,直到用户手动closures它?