IOS开发实现录音功能
导入框架:
#import<AVFoundation/AVFoundation.h>
声明全局变量:
@interfaceViewController()<AVAudioRecorderDelegate>
{
AVAudioRecorder*audioRecorder;
}
@end
在ViewDidLoad中:
UIButton*button=[UIButtonbuttonWithType:UIButtonTypeCustom]; button.frame=CGRectMake(100,100,100,100); [buttonsetTitle:@"TICK"forState:UIControlStateNormal]; button.backgroundColor=[UIColorbrownColor]; [buttonaddTarget:selfaction:@selector(startAudioRecoder:)forControlEvents:UIControlEventTouchUpInside]; [self.viewaddSubview:button];
按钮的触发事件
-(void)startAudioRecoder:(UIButton*)sender{
sender.selected=!sender.selected;
if(sender.selected!=YES){
[audioRecorderstop];
return;
}
//URL是本地的URLAVAudioRecorder需要一个存储的路径
NSString*name=[NSStringstringWithFormat:@"%d.aiff",(int)[NSDatedate].timeIntervalSince1970];
NSString*path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES).firstObjectstringByAppendingPathComponent:name];
NSError*error;
//录音机初始化
audioRecorder=[[AVAudioRecorderalloc]initWithURL:[NSURLfileURLWithPath:path]settings:@{AVNumberOfChannelsKey:@2,AVSampleRateKey:@44100,AVLinearPCMBitDepthKey:@32,AVEncoderAudioQualityKey:@(AVAudioQualityMax),AVEncoderBitRateKey:@128000}error:&error];
[audioRecorderprepareToRecord];
[audioRecorderrecord];
audioRecorder.delegate=self;
/*
1.AVNumberOfChannelsKey通道数通常为双声道值2
2.AVSampleRateKey采样率单位HZ通常设置成44100也就是44.1k
3.AVLinearPCMBitDepthKey比特率8162432
4.AVEncoderAudioQualityKey声音质量
①AVAudioQualityMin=0,最小的质量
②AVAudioQualityLow=0x20,比较低的质量
③AVAudioQualityMedium=0x40,中间的质量
④AVAudioQualityHigh=0x60,高的质量
⑤AVAudioQualityMax=0x7F最好的质量
5.AVEncoderBitRateKey音频编码的比特率单位Kbps传输的速率一般设置128000也就是128kbps
*/
NSLog(@"%@",path);
}
代理方法:
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder*)recordersuccessfully:(BOOL)flag{
NSLog(@"录音结束");
//文件操作的类
NSFileManager*manger=[NSFileManagerdefaultManager];
NSString*path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject];
//获得当前文件的所有子文件subpathsAtPath
NSArray*pathlList=[mangersubpathsAtPath:path];
//需要只获得录音文件
NSMutableArray*audioPathList=[NSMutableArrayarray];
//遍历所有这个文件夹下的子文件
for(NSString*audioPathinpathlList){
//通过对比文件的延展名(扩展名尾缀)来区分是不是录音文件
if([audioPath.pathExtensionisEqualToString:@"aiff"]){
//把筛选出来的文件放到数组中
[audioPathListaddObject:audioPath];
}
}
NSLog(@"%@",audioPathList);
}