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: 1], 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])
{ //代码无法进入这里 }
经过尝试发现,
使用 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);
}
iOS开发-解决AVAudioRecorder录音文件无法保存的问题
最新推荐文章于 2022-10-10 08:30:19 发布