处于深度睡眠模式时,声音和Nstimer停止了吗? [英] sound and Nstimer stopped when iphone is in deepsleepmode?

查看:118
本文介绍了处于深度睡眠模式时,声音和Nstimer停止了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个使用nstimer和avaudioplayer播放声音的应用程序,但是当电话处于深度睡眠模式时,声音和计时器都会停止.如何解决此问题?

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?

这是播放音频的代码

-(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];
}
}

推荐答案

为了防止屏幕锁定时应用进入睡眠状态,您必须将音频会话设置为kAudioSessionCategory_MediaPlayback类型.

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.

这是一个例子:

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 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.

我在这里有一个代码示例:防止iPhone进入睡眠状态

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

这篇关于处于深度睡眠模式时,声音和Nstimer停止了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆