打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
iOS开发

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);}

 

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
IOS AVFoundation的录音与播放
iOS 录音,播放,转码MP3,上传语音文件
iOS开发 录音以及播放 AVAudioRecorder
ios网络学习
iOS应用开发最佳实践:编写高质量的Objective
ios常用的几个动画代码
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服