做一个简易的录音器

来源:互联网 发布:linux网络接口详解 编辑:程序博客网 时间:2024/04/30 07:28

整体看着,录音跟音乐播放很相似,只是它们的播放器的对象不同录音的是AVAudioRecorder

不用多少举个例子吧

    是通过一个按钮来控制开始录音和停止录音

1、导入框架#import<AVFoundation/AVFoundation.h>
 AVAudioRecorder *audioRecorder;//声明一个录音控制器对象
2、写一个button来判断开始录音与停止录音
UIButton *button = [UIButtonbuttonWithType:UIButtonTypeCustom];
    button.
frame =CGRectMake(100,100,100,100);
    [button
setTitle:@"开始"forState:UIControlStateNormal];
    [button
setTitle:@"停止"forState:UIControlStateSelected];
    [button
setBackgroundColor:[UIColorlightGrayColor]];
    [button
addTarget:selfaction:@selector(startAudioRecorder:)forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:button];
-(void)startAudioRecorder:(UIButton *)sender{
    sender.
selected = !sender.selected;
   
if (sender.selected == NO) {
        [
audioRecorder stop];
       
return;
    }
   
NSString *time = [NSStringstringWithFormat:@"%d.aiff", (int)[NSDatedate].timeIntervalSince1970];
   
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject]stringByAppendingPathComponent:time];
   
NSLog(@"%@",path);
   
/**
    
创建一个对象
     url
是个本地存储路径
     */

   
NSError *error;
你可以通过调整下面的值,改变录音的声音
   
/**
     AVNumberOfChannelsKey:@2
通道数通道一般为双通道
     AVSampleRateKey:@44100
采样率单位hz通常设置成44100 44.1kHZ跟音频的质量有关
     AVLinearPCMBitDepthKey:@32
比特率 8 16 24 32
     AVEncoderAudioQualityKey:@(AVAudioQualityMax)
需要一个枚举
     AVAudioQualityMin    = 0,      
最小的
     AVAudioQualityLow    = 0x20,   
比较低的
     AVAudioQualityMedium = 0x40,   
中等的
     AVAudioQualityHigh   = 0x60,   
高的
     AVAudioQualityMax    = 0x7F    
最大的
     AVEncoderBitRateKey:@128000
音频编码的比特率单位是BPS传输率有一定的影响对音质 一般为128000BPS 128kBPS
     */

   
audioRecorder = [[AVAudioRecorderalloc]initWithURL:[NSURLfileURLWithPath:path]settings:@{AVNumberOfChannelsKey:@2,AVSampleRateKey:@44100,AVLinearPCMBitDepthKey:@32,AVEncoderAudioQualityKey:@(AVAudioQualityMax),AVEncoderBitRateKey:@128000}error:&error];
   
audioRecorder.delegate =self;
    [
audioRecorderprepareToRecord];//预录音
    [
audioRecorderrecord];//开始录音
   
}
 3、把录好的音频文件给保存好 利用代理方法代理是AVAudioRecorderDelegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
   
//文件操作的一个类,有移动、删除、命名等操作
   
NSFileManager *file = [NSFileManagerdefaultManager];
   
//获得当前文件的所有子文件  subpathsAtPath通过这个方法
  
NSArray *pathList = [filesubpathsAtPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject]];
   
//只获得录音文件遍历这个当前文件的子文件
   
NSMutableArray *audioPathList = [NSMutableArrayarray];
   
for (NSString *audioPathin pathList) {
       
//通过对比文件的延展名(扩展名或者尾缀)来区分是不是录音文件
       
if ([audioPath.pathExtensionisEqualToString:@"aiff"]) {
           
//把录音文件添加到录音文件数组中
            [audioPathList
addObject:audioPath];
        }
       
    }
   
}//完成录音
 
通过nslog出来的路劲查找到我们说话录下来的音频文件,双击就可以播放了。
想要看效果吗,赶快试试吧





0 0
原创粉丝点击