iOS开发-解决AVAudioRecorder录音文件无法保存的问题

时间:2022-11-28 22:31:14
iOS开发-解决AVAudioRecorder录音文件无法保存的问题

我们在开发iOS客户端APP时,有时候会用到录音的功能,一般会使 AVAudioRecorder 这个类。如下面这样:

@interface MyViewController : UIViewController<AVAudioRecorderDelegate>
{
AVAudioRecorder *recorder;
NSURL *url;
AVAudioPlayer *avPlay;
}
//初始化配置
- (void)audio
{
NSDictionary *recordSettings =
[[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt: ], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityMax],
AVEncoderAudioQualityKey,
nil]; NSString *strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; //记录录音文件
url = [NSURL fileURLWithPath:[NSString string WithFormat:@"%@/file.caf", strUrl]]; NSError *error;
recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSettings error:&error]; recorder.meteringEnabled = YES;
recorder.delegate = self;
}
//录音
- (void)record
{
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryError];
NSError *activationError = nil;
[session setActive:YES error:&activationError]; if ([recorder prepareToRecord]) {
[recorder record];
}
}
//播放录音
- (void)playRecordSound
{
if (self.avPlay.playing) {
[self.avPlay stop];
return;
}
AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
self.avPlay = player;
[self.avPlay play];
}

这样就实现了录音和播放功能。

但我试图把录音文件另存或上传至远程服务器的时候,却遇到困难,无法检测到文件的存在,例如:

if ([[NSFileManager defaultManager] fileExistsAtPath: url.path]) {

    //代码无法进入这里
}

或者:

if ([[NSFileManager defaultManager] copyItemAtPath:url.path toPath:newfilePath error:nil]) {

    //代码无法进入这里
}

经过尝试发现,NSFileMangeer类无法访问的文件路径,NSData类却可以。于是,用NSData类读取录音文件路径,再写入新路径,即解决问题。

NSData *mydata = [NSData dataWithContentsOfFile:url.path];
BOOL isSaved = [mydata writeToFile:newfilePath atomically:NO];
if (isSaved) {
NSLog(@"%@文件成功保存!", newfilePath);
}

然后再验证新文件就是存在的了。

if ([[NSFileManager defaultManager] fileExistsAtPath:newfilePath]) {
NSLog(@"%@文件验证有效", newfilePath);
}