当前位置:   article > 正文

Record Audio(录音)_record_audio

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 */

    }

    

}




声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/283826
推荐阅读
  

闽ICP备14008679号