我在应用程序处于后台时正在录制(将音频添加到后台模式),它将无限期地录制,并且应用程序在后台保持活动状态。
我希望能够让应用程序在后台保持活动状态,并每隔 30 分钟录制一个 30 秒的声音片段。
我曾尝试NSTimer
与AVAudioRecorder
'srecordForDuration:
方法结合使用,但该应用程序在启动之前就被杀死了NSTimer
。有任何想法吗?
以下代码在后台工作,每 5 秒记录 5 秒,但如果我将 scheduleTimerWithTimeInterval 增加到 1 分钟,它就不起作用。
- (void)viewDidLoad
{
[super viewDidLoad];
// retrieve avaudiosession instance
_session = [ AVAudioSession sharedInstance];
// set category
NSError *errRet;
[_session setCategory:AVAudioSessionCategoryPlayAndRecord error:&errRet];
[_session setActive:YES error:&errRet];
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:@"sound.caf"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *recordSettings = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0],
AVSampleRateKey,
nil];
NSError *error = nil;
_audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (error)
{
NSLog(@"error: %@", [error localizedDescription]);
} else {
[self recordAudio];
NSTimer* timer;
timer=[NSTimer scheduledTimerWithTimeInterval: 10.0 target:self selector:@selector(recordAudio) userInfo:nil repeats: YES];
NSLog(@"timer fired");
}
}
- (IBAction)recordAudio{
if (!_audioRecorder.recording)
{
NSError *errRet;
[_session setCategory:AVAudioSessionCategoryRecord error:&errRet];
[_session setActive:YES error:&errRet];
//_play.enabled = NO;
[_audioRecorder recordForDuration:5.0];
NSLog(@"Finished Recording");
}
}