Sound and Nstimer stopped when the iphone is in deep light?

I am creating an application in which I use nstimer and avaudioplayer to play sound, but the sound and timer stop when the phone is in deep sleep mode. How to solve this problem?

here is the code for playing audio

-(void)PlayTickTickSound:(NSString*)SoundFileName { //Get the filename of the sound file: NSString *path = [NSString stringWithFormat:@"%@%@",[[NSBundle mainBundle] resourcePath],[NSString stringWithFormat:@"/%@",SoundFileName]];// @"/Tick.mp3"]; //Get a URL for the sound file NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO]; NSError *error; if(self.TickPlayer==nil) { self.TickPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:filePath error:&error]; // handle errors here. self.TickPlayer.delegate=self; [self.TickPlayer setNumberOfLoops:-1]; // repeat forever [self.TickPlayer play]; } else { [self.TickPlayer play]; } } 
+2
objective-c xcode nstimer avaudioplayer
Nov 17 '09 at 15:14
source share
1 answer

To prevent the application from sleeping when the screen is locked, you must set your audio session to be of type kAudioSessionCategory_MediaPlayback.

Here is an example:

 UInt32 category = kAudioSessionCategory_MediaPlayback; OSStatus result = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category); if (result){ DebugLog(@"ERROR SETTING AUDIO CATEGORY!\n"); } result = AudioSessionSetActive(true); if (result) { DebugLog(@"ERROR SETTING AUDIO SESSION ACTIVE!\n"); } 

If you do not set the audio session category, your application will sleep.

This will cause the application to not sleep as long as you continue to play audio. If you stop playing audio and the screen is still locked, the application will go into sleep mode and your timers will be paused.

If you want the application not to weaken indefinitely, you will need to play a β€œquiet” audio file so that it does not wake up.

I have an example code here: iPhone Prevention of Sleep

+4
Nov 20 '09 at 1:53
source share



All Articles