Use AVAudioRecorder, AVAudioSession and the AVAudioPlayer

Permissions audio recording needs , you need to set the plist file: Privacy - Microphone Usage Description

AVAudioRecorder video recording, AVAudioPlayer video playback, AVAudioSession we also need to understand, it can be achieved by controlling the current context of the App audio resources, such as plug headphones, answer the phone, whether audio, and other data such as remixes, often we encounter login problems, if there are problems, or adds, you can contact me, I should have used the transient covered the

 

#import <the AVFoundation / AVFoundation.h> 
#import <Masonry.h> 
@interface AVAudioVC () <AVAudioRecorderDelegate> 
@Property (nonatomic, strong) * AVAudioRecorder audiorecorder; // audio recording 

@property (nonatomic, strong) UIButton * audioRecorderBeginBtn; // audio recording start 
@property (nonatomic, strong) UIButton * audioRecorderPauseBtn; // pause recording 
@property (nonatomic, strong) UIButton * audioRecorderStopBtn; // stop recording audio 
/ ** AVAudioSession we also need to know can be achieved by it to control the current context of audio resources App, such as plug headphones, answer the phone, whether audio, and other data such as remixes, often some of the problems we encountered, such as these below: 
 1, is recording or playing? 
 
 2, pressed the mute button when the system how to behave? 
 
 3, is still playing a sound from inside the handset from the speaker? 
 
 4, how to plug the headset performance? 
 
 5, how to call after / alarm clock rang performance? 
 
 6, how to start App after other audio performance? * / 
@Property (nonatomic, strong) * AVAudioSession the session; 
The @Property (nonatomic, strong) AVAudioPlayer * Player; // player 
@end

@implementation AVAudioVC

-(AVAudioSession *)session{
    if(!_session){
        //AVAudioSession是一个单例 实例化
        _session =[AVAudioSession sharedInstance];
        
        NSError *sessionError;
      
        
        if (_session == nil) {
            
            NSLog(@"Error creating session: %@",[sessionError description]);
            
        }else{
            //激活session
            [_session setActive:YES error:nil];
            
        }
    }
    return _session;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setView];
    
    //设备改变
    [[NSNotificationCenter defaultCenter] addObserver: Self Selector: @selector (handleRouteChange :) name: AVAudioSessionRouteChangeNotification Object: [AVAudioSession sharedInstance]]; 
    // The current flow is interrupted 
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector (audioInterruption: ) name: AVAudioSessionInterruptionNotification Object: [AVAudioSession sharedInstance]]; 
} 

// pull headphones, etc. 
- (void) handleRouteChange: (NSNotification *) {Notl 
    
    NSDictionary * info = noti.userInfo; 
    AVAudioSessionRouteChangeReason reason = [info [AVAudioSessionRouteChangeReasonKey] unsignedIntegerValue]; 
    / ** 
     AVAudioSessionRouteChangeReasonUnknown: unknown reason 
     AVAudioSessionRouteChangeReasonNewDeviceAvailable: new equipment available 
     AVAudioSessionRouteChangeReasonOldDeviceUnavailable: old equipment not available 
     AVAudioSessionRouteChangeReasonCategoryChange: category changed 
     AVAudioSessionRouteChangeReasonOverride: app reset output setting 
     AVAudioSessionRouteChangeReasonWakeFromSleep: wake up from sleep transited calls 
     AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory: no suitable apparatus the current category 
     AVAudioSessionRouteChangeReasonRouteConfigurationChange: Router Configuration change 
     * / 
    // old audio device disconnect 
    IF (== reason AVAudioSessionRouteChangeReasonOldDeviceUnavailable) { 
        
        // Get the description of a line of information on the type of output apparatus and acquires a line 
        AVAudioSessionRouteDescription * previousRoute = info [AVAudioSessionRouteChangePreviousRouteKey] ;
        * = PreviousRoute.outputs previousOutput AVAudioSessionPortDescription [0]; 
        NSString * portType = previousOutput.portType; 
        
        IF ([portType as isEqualToString: AVAudioSessionPortHeadphones]) { 
             
            // here pause playback
        } 
    } 
} 
/ * Interrupt audio playback system monitor 
call pause 
QQ micro-channel speech pauses 
other music software occupies 
 * / 
- (void) audioInterruption: (NSNotification *) NotI { 
    
    NSDictionary * info = noti.userInfo; 
    AVAudioSessionInterruptionType of the type = [info [AVAudioSessionInterruptionTypeKey] unsignedIntegerValue]; 
    
    IF (of the type == AVAudioSessionInterruptionTypeBegan) { 
        // an interrupt start, we should pause playback and acquisition value of AVAudioSessionInterruptionTypeEnded indicate the interruption is over, we can continue to play and acquisition. 
    } Else {
        // current value AVAudioSessionInterruptionOptionShouldResume represent only one at this time should be restored to continue playing and collecting. 
        AVAudioSessionInterruptionOptions options = [info [AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        IF (Options == AVAudioSessionInterruptionOptionShouldResume) { 
            
        } 
    } 
} 


/ ** 
 All controls initialization 
 * / 
- (void) {the setView 
    
    // Audio Recording 
    the UIView audioRecorderView * = [the UIView new new]; 
    audioRecorderView.layer.cornerRadius = 5.0f; 
    audioRecorderView. = layer.borderColor [UIColor blackColor] .CGColor; 
    audioRecorderView.layer.borderWidth = 1.0f; 
    [self.view addSubview: audioRecorderView]; 
    audioRecorderView.backgroundColor = [UIColor redColor]; 
    [audioRecorderView mas_makeConstraints: ^ (* MASConstraintMaker the make) {
        make.top.offset(90);
        make.left.offset(12);
        make.right.offset(-12);
        make.height.offset(74);
    }];
    
    
    
    UILabel *audioRecorderTitleLab = [UILabel new];
    audioRecorderTitleLab.text = @"音频录制";
    [audioRecorderView addSubview:audioRecorderTitleLab];
    [audioRecorderTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.height.offset(30);
    }];
    
    
    self.audioRecorderBeginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.audioRecorderBeginBtn setTitle:@"开始" forState:UIControlStateNormal];
    [self.audioRecorderBeginBtn addTarget:self action:@selector(audioRecorderBeginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [audioRecorderView addSubview:self.audioRecorderBeginBtn];
    [self.audioRecorderBeginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(audioRecorderTitleLab.mas_bottom);
        make.left.offset(12);
        make.bottom.offset(0);
        make.width.offset(80);
    }];
    
    self.audioRecorderPauseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.audioRecorderPauseBtn setTitle:@"暂停" forState:UIControlStateNormal];
    [self.audioRecorderPauseBtn setTitle:@"开始" forState:UIControlStateSelected];
    
    [self.audioRecorderPauseBtn addTarget:self action:@selector(audioRecorderPauseBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [audioRecorderView addSubview:self.audioRecorderPauseBtn];
    [self.audioRecorderPauseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.audioRecorderBeginBtn.mas_right).offset(12);
        make.size.equalTo(self.audioRecorderBeginBtn);
        make.bottom.equalTo(self.audioRecorderBeginBtn.mas_bottom);
    }];

    
    
    self.audioRecorderStopBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.audioRecorderStopBtn setTitle:@"停止" forState:UIControlStateNormal];
    [self.audioRecorderStopBtn addTarget:self action:@selector(audioRecorderStopBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [audioRecorderView addSubview:self.audioRecorderStopBtn];
    [self.audioRecorderStopBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo (self.audioRecorderPauseBtn.mas_right) .offset (12 is); 
        make.size.equalTo (self.audioRecorderBeginBtn); 
        make.bottom.equalTo (self.audioRecorderBeginBtn.mas_bottom); 
    }]; 
    
    
    // audio player 
    
    

} 
/ ** 
 录音开始
 */
- (void) {audioRecorderBeginBtnClick 
    / ** 
     about two initialization method, two methods similar to, configuration information NSDictionary 
    - (nullable instancetype) initWithURL: ( NSURL *) url settings: (NSDictionary <NSString *, id > *) Settings error: (the NSError **) outerror; 
    - (Nullable instanceType) initWithURL: (NSURL *) the format URL: (AVAudioFormat *) the format error: (the NSError **) outerror API_AVAILABLE (MacOS (10.12), iOS (10.0 ), watchos (4.0)) API_UNAVAILABLE (tvos); 
     
     ready to start recording 
     - (BOOL) prepareToPlay; 
     pause recording 
     - (void) pause; 
     stop recording 
     - (void) sTOP; 
     
     * / 
    IF (self.audioRecorderBeginBtn.selected) { 
        // already begun 
        NSLog (@ "- ----------------------------- recording has started, does not need to repeat recording "); 
       
    } the else { 
        
        / **
         Setting session attribute 
         AVAudioSessionCategoryAmbient: When the user lock screen or mute when the mute, support mix, only supports playback 
         AVAudioSessionCategorySoloAmbient: When the user lock screen or mute when the mute, does not support mixing, only supports playback 
         AVAudioSessionCategoryPlayback: When the user lock screen or mute when not muted, and does not support mixing, only supports playback 
         AVAudioSessionCategoryRecord: when the user lock screen or mute when not muted, and does not support mixing, recording only support 
         AVAudioSessionCategoryPlayAndRecord: when the user lock screen or mute when not muted, support mix , you can record and play 
        // start 
        self.audioRecorder = [[ AVAudioRecorder alloc] initWithURL: [self getSavePath ] settings: [self getAudioSetting] error: nil]; 
         AVAudioSessionCategoryAudioProcessing: do not support
         AVAudioSessionCategoryMultiRoute: lock screen when the user is not muted or muted when not support mixing, recording and playback can be 
         * / 
        [self.session setCategory: AVAudioSessionCategoryPlayAndRecord error: nil];
        
        
        Self = self.audioRecorder.delegate; 
// self.audioRecorder.meteringEnabled = YES; // Open audio measurements 
        [self.audioRecorder prepareToRecord]; // 
        [self.audioRecorder Record]; 
        
// 
        [self.audioRecorder updateMeters]; 
        [Self .audioRecorder averagePowerForChannel: 0]; // specified channel decibel value 
        [self.audioRecorder peakPowerForChannel: 0]; // average decibel value 
        NSLog (@ "------------------- ------------ @ recording has started% ", self.audioRecorder); 
    } 
    self.audioRecorderBeginBtn.selected = YES; 
    
    
    
    dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (an int64_t) (2 * NSEC_PER_SEC)), dispatch_get_main_queue (), ^ {
         NSLog (@ "isRecording: 1 ---------------------------------------- :% d ", self.audioRecorder.isRecording); 
    }); 
} 


/ * 
 audio stored URL 
 * / 
- (NSURL *) getSavePath { 
    NSString urlStr * = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
    urlStr = [urlStr stringByAppendingPathComponent: @ "myRecord.caf"]; 
    NSLog (@ "File path:% @", urlStr); 
    NSURL * URL = [NSURL fileURLWithPath: urlStr]; 
    return URL; 
} 
/ * 
 @return recording settings 
 * / 
-(NSDictionary *)getAudioSetting{
    NSMutableDictionary DICM * = [ Dictionary NSMutableDictionary]; 
    // set the recording format 
    [dicM setObject: @ (kAudioFormatLinearPCM) forKey: AVFormatIDKey];
    // set the recording sample rate, sampling rate 8000 is a telephone, is enough for the average recordings 
    [DICM the setObject: @ (8000) forKey: AVSampleRateKey]; 
    // set the channel, here in mono 
    [dicM setObject: @ (1) forKey: AVNumberOfChannelsKey]; 
    // number of bits for each sample point, divided 8,16,24,32 
    [DICM the setObject: @ (. 8) forKey: AVLinearPCMBitDepthKey]; 
    // float whether sampling 
    [dicM setObject: @ (YES ) forKey: AVLinearPCMIsFloatKey]; 
    // recording quality 
    [DICM the setObject: [the NSNumber numberWithInt: AVAudioQualityHigh] forKey: AVEncoderAudioQualityKey]; 
    
    // .... other settings 
    return DICM; 
} 


/ ** 
 recording pause 
 * / 
- (void) audioRecorderPauseBtnClick { 
    IF (self.audioRecorderPauseBtn.selected) { 
    IF (self.audioRecorder!) {
        return; 
    } 
/ * audioRecorderDidFinishRecording: successfully: IS A Called When recording or has been Finished stopped. This method is NOT called if the recorder is stopped due to an interruption. * /

        // audio recording start 
         [self.audioRecorder Record]; 
    } the else { 
        // record audio pause 
         [self.audioRecorder PAUSE]; 
    } 
    self.audioRecorderPauseBtn.selected = self.audioRecorderPauseBtn.selected;! 
} 


/ ** 
 audio recording stop 
 * / 
- (void) audioRecorderStopBtnClick { 
   
    // if still recorded 
    [self.audioRecorder STOP]; 
    self.audioRecorderBeginBtn.selected = NO; 

} 


#pragma Mark AVAudioRecorderDelegate 

- (void) audioRecorderDidFinishRecording: (AVAudioRecorder *) successfully recorder: (BOOL) In Flag { 
    // the recording is finished 
    NSLog (@ "--------------: the recording is finished");
    
//    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[self getSavePath] error:nil];
//    if ([audioPlayer prepareToPlay] == YES &&
//        [audioPlayer play] == YES) {
//        NSLog(@"--------------------------------:开始播放");
//    }else{
//         NSLog(@"--------------------------------:失败");
//    }

    
}

/* if an error occurs while encoding it will be reported to the delegate. */
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error{
    NSLog(@"--------------:录音编码发生错误");
}


/**
 音频播放
 */
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.audioRecorder stop];
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[self getSavePath] error:nil];
//    NSLog(@"%li",self.player.data.length/1024);
    [self.session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    if([self.player prepareToPlay] == YES && [self.player play] == YES){
        NSLog(@"-------------------:播放");
    }else{
         NSLog(@"-------------------:停止");
    }
  
    
}


-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end

 

Guess you like

Origin www.cnblogs.com/hualuoshuijia/p/11512990.html
use
use