Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

objective c - sound and Nstimer stopped when iphone is in deepsleepmode?

I am creating an application in which I'm using nstimer and avaudioplayer to play sound,but both sound and timer stops when phone is in deep sleep mode.how to solve this issue?

here is the code to play 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];
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to prevent an app from going to sleep when the screen is locked, you must set your audio session to be of type kAudioSessionCategory_MediaPlayback.

Here's an example:

UInt32 category = kAudioSessionCategory_MediaPlayback;
OSStatus result = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
                                        sizeof(category), &category);

if (result){
    DebugLog(@"ERROR SETTING AUDIO CATEGORY!
");
}

result = AudioSessionSetActive(true);
if (result) {
    DebugLog(@"ERROR SETTING AUDIO SESSION ACTIVE!
");
}

If you don't set the audio session category, then your app will sleep.

This will only continue to prevent the app from being put to sleep as long as you continue to play audio. If you stop playing audio and the screen is still locked, the app will go to sleep and your timers will be paused.

If you want the app to remain awake indefinitely, you'll need to play a "silent" audio file to keep it awake.

I have a code example of this here: Preventing iPhone Sleep


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...