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

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


 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值