Record Audio(录音)

1。导入 #import <AVFoundation/AVFoundation.h> 

2。实现协议<AVAudioRecorderDelegate>


e.g.

@property (nonatomic, strong)AVAudioRecorder *audioRecorder;

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;


//录音后保存的音频文件的路径

- (NSURL *) audioRecordingPath{   

    NSFileManager *fileManager = [[NSFileManager alloc] init];   

    NSURL *documentsFolderUrl = [fileManager URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask

                                 appropriateForURL:nil create:NO  error:nil];

    NSURL *url =[documentsFolderUrl  URLByAppendingPathComponent:@"Recording.m4a"];

    return url;  

}

/* 录音的选项设置 字典形式 */ 

- (NSDictionary *) audioRecordingSettings{  

    NSDictionary *dic = @{

                          AVFormatIDKey : @(kAudioFormatAppleLossless),  //录音格式  kAudioFormatLinearPCM,kAudioFormatAppleLossless

                          AVSampleRateKey : @(44100.0f),  //采样率   

                          AVNumberOfChannelsKey : @1,    //信道的数目

                          AVEncoderAudioQualityKey : @(AVAudioQualityLow), //录音的质量 AVAudioQualityMin,AVAudioQualityLow,

                                                                          // AVAudioQualityMedium,AVAudioQualityHigh,AVAudioQualityMax

                          };

    return dic;   

}


- (IBAction)actionRecord:(id)sender {

    /* 请求录音权限 */

    AVAudioSession *session = [AVAudioSession sharedInstance];   

    [session setCategory:AVAudioSessionCategoryPlayAndRecord

             withOptions:AVAudioSessionCategoryOptionDuckOthers

                   error:nil];

    [session requestRecordPermission:^(BOOL granted) {

        if (granted) {

            NSLog(@"permission ok to record audio");

            [self startRecordingAudio];

        }else {

            NSLog(@"We don't have permission to record audio.");

        }      

    }];

}

- (void) startRecordingAudio{   

    NSError   *error = nil;    

    NSURL *audioRecordingURL = [self audioRecordingPath];  

    self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:audioRecordingURL 

                               settings:[self audioRecordingSettings] error:&error];   

    if (self.audioRecorder != nil){       

        self.audioRecorder.delegate = self;

        if ([self.audioRecorder prepareToRecord] &&

            [self.audioRecorder record]){

            NSLog(@"Successfully started to record.");           

            /* 5秒后停止录音 */

            [self performSelector:@selector(stopRecordingOnAudioRecorder:)

                       withObject:self.audioRecorder

                      afterDelay:5.0f];           

        } else {

            NSLog(@"Failed to record.");

            self.audioRecorder = nil;

        }

        

    } else {

        NSLog(@"Failed to create an instance of the audio recorder.");

    }

    

}

- (void) stopRecordingOnAudioRecorder:(AVAudioRecorder *)paramRecorder{

    NSLog(@"stop to record");

    [paramRecorder stop];

}

//录音被打断

- (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder{  

    NSLog(@"Recording process is interrupted");  

}

- (void)audioRecorderEndInterruption:(AVAudioRecorder *)recorder withOptions:(NSUInteger)flags{

    if (flags ==AVAudioSessionInterruptionOptionShouldResume){

        NSLog(@"Resuming the recording...");

        [recorder record];

    }   

}

//结束时要释放,不论是录音,还是播放

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder  successfully:(BOOL)flag{  

    if (flag){      

        NSLog(@"Successfully stopped the audio recording process.");       

    } else {

        NSLog(@"Stopping the audio recording failed.");

    }

    self.audioRecorder = nil;  

}

//------play---------

- (IBAction)actionPlay:(id)sender {

    /* 获取录音 */

    NSError *playbackError = nil;

    

    NSError *readingError = nil;

    NSData  *fileData =  [NSData dataWithContentsOfURL:[self audioRecordingPath]

                          options:NSDataReadingMapped error:&readingError];

    self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData  error:&playbackError];

    

    if (self.audioPlayer != nil){

        self.audioPlayer.delegate = self;

        if ([self.audioPlayer prepareToPlay] &&  [self.audioPlayer play]){

            NSLog(@"Started playing the recorded audio.");

        } else {

            NSLog(@"Could not play the audio.");

        }

        

    } else {

        NSLog(@"Failed to create an audio player.");

    }

}

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{  

    /* The audio session has been deactivated here */

}


- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player  withOptions:(NSUInteger)flags{   

    if (flags == AVAudioSessionInterruptionOptionShouldResume){

        [player play];

    } 

}


- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player  successfully:(BOOL)flag{   

    if (flag){

        NSLog(@"Audio player stopped correctly.");

    } else {

        NSLog(@"Audio player did not stop correctly.");

    }  

    if ([player isEqual:self.audioPlayer]){

        self.audioPlayer = nil;

    } else {

        /* This is not our player */

    }

    

}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值