我有一个应用程序可以监控背景音频级别而无需录制到文件中。我使用写入/ dev / null的技巧来实现这一目标。
此代码适用于iOS 6的iPhone 3GS,iOS 6和iOS 7的iPhone 4,以及iOS 7和iPhone Retina(4英寸64位)的模拟器。
然而,当我在真正的iPhone 5s上试用时,录音机似乎会暂时捕捉音频,然后默默地死掉。
这是代码:
// Inititalize the audio
NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey,
nil];
NSError *error;
recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
if (recorder) {
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
[recorder record];
levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.03 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];
// peakLevelTimer = [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self selector: @selector(peakLevelTimerCallback:) userInfo: nil repeats: YES];
} else {
NSLog(@"There was an error setting up the recorder.");
NSLog([error description]);
}
任何想法可能会发生什么?
有人可以建议解决方法吗?写入真实文件有效,但我不想填充设备上的任何空间只是为了监听音频。有没有办法写入一个只能蒸发到空气中的小文件缓冲区?有效地实现我自己的/ dev / null吗?
答案 0 :(得分:7)
在测试我的iOS 7应用程序时遇到了同样的问题。
我通过创建一个初始文件来解决缺少/ dev / null的问题,然后在录制开始后删除了几秒钟。录音仍然继续适用于我的应用程序,并且没有存储数据文件。
- (void)startRecording
{
// New recording path.
NSString *recorderFilePath = [NSString stringWithFormat:@"%@/%@.caf", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"], @"cache"];
NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
AVAudioRecorder recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
if([recorder prepareToRecord])
{
[recorder record];
NSTimer deleteFileTimer = [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(removeRecordingFile) userInfo:nil repeats:NO];
}
}
- (void)removeRecordingFile
{
// Remove the data file from the recording.
NSString *recorderFilePath = [NSString stringWithFormat:@"%@/%@.caf", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"], @"cache"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
BOOL success = [fileManager removeItemAtPath:recorderFilePath error:&error];
if(success)
{
NSLog(@"Deleted recording file");
}
else
{
NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
}
}
答案 1 :(得分:0)
您需要更改:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:NULL];
为:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:NULL];