屏幕closures播放声音/不要让iPhone进入睡眠状态

所以我有一个应用程序,我想保持它的工作,即使屏幕closures。 以前,当我想这样做时,我使用了这个技巧 – 我在背景(AudioServicesPlaySystemSound)的循环中播放无声/空声音,所以如果用户按下开/关button,应用程序仍然在后台工作 – 所以它永远不会允许iPhone进入睡眠模式 – 它只是closures了屏幕,也许像WiFi或蓝牙(和我所记得的iPod Touch加速度计)的东西。 它的工作。 我想在我的新应用程序中使用相同的技巧,但是当我现在testing它似乎不工作了。 即使在屏幕closures的情况下,后台播放的声音(当我用一些声音replace“空的”audio文件时,我可以听到它播放),但是它应该播放的声音(使用AVAudioPlayer)不会播放(即使当我打开屏幕再次)。 我不知道在哪一点停止工作(它确实工作在3.x操作系统)。 难道我做错了什么? 苹果是否改变/修复了即使屏幕closures也能让你的应用程序工作的“黑客”? 是否有另一种方式让设备进入睡眠状态(并减less电池消耗),但继续工作?

这是我用来播放背景/静音的代码:

-(void) playSilentSound { CFBundleRef mainBundle = CFBundleGetMainBundle (); CFURLRef silentUrl = CFBundleCopyResourceURL (mainBundle, CFSTR ("silence"), CFSTR ("aiff"), NULL); AudioServicesCreateSystemSoundID (silentUrl, &silentSound); silentTimer = [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self selector:@selector(playSilence) userInfo: nil repeats: YES]; } -(void) playSilence { AudioServicesPlaySystemSound (silentSound); } 

这就是我如何播放即使屏幕closures也应播放的声音:

 -(BOOL) playSound: (NSString *) path withLoops: (BOOL) loops stopAfter: (int) seconds { NSError *error; player = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath: path] error: &error]; player.delegate = self; player.numberOfLoops = 0; player.volume = volume; secondsPlayed = 0; loop = loops; BOOL played = [player play]; if(played && seconds > 0) { timer = [[NSTimer scheduledTimerWithTimeInterval: 0.5 target: self selector: @selector(stopPlaying:) userInfo: [NSNumber numberWithInt: seconds] repeats: YES] retain]; secondsLimit = seconds; } else { secondsLimit = -1; } } -(void) stopPlaying:(NSTimer*)theTimer { if(secondsLimit > 0 && (secondsPlayed + [player currentTime]) >= secondsLimit) { [player stop]; [timer release]; timer = nil; } } - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)sender successfully:(BOOL)flag { if(sender == player) { if(flag) { secondsPlayed += sender.duration; } if(loop) { [player play]; } } } 

代码有点复杂 – 可能只是前几行 – 这样做,所以你只能播放X秒的声音(如果声音比X短,它将播放几个循环,直到总时间> = X )。 当然屏幕还没有开启,当然一切正常。

另外 – 如果你发现代码在你的项目中很有用(比如playSound:withLoops:stopAfter 🙂 – 随意使用它(但是如果你给我发信息会很酷,所以我知道我帮了:))。

所以答案是设置会话类别。 有些类别只是在设备被locking时closures声音。 对我来说最好的select是AVAudioSessionCategoryPlayback

 [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil]; 

我不知道有关苹果的东西,但在iOS 4中,现在有官方的方法可以在后台继续做你应该利用的东西。