AVAudioRecorder、AVAudioSessionとAVAudioPlayerを使用します

権限のオーディオ録音のニーズマイク使用法の説明-プライバシー:あなたはplistファイルを設定する必要があります

ビデオ録画、AVAudioPlayerのビデオ再生、我々はまた、それは、このようなプラグのヘッドフォンとしてのAppオーディオリソースの現在の状況を制御することによって達成することができ、理解する必要がAVAudioSession、電話に応答し、オーディオかどうか、そして、そのようなリミックスなど、他のデータ、多くの場合、我々が遭遇AVAudioRecorderログインの問題は、そこに問題がある、または追加した場合、あなたは私に連絡することができ、私は一時的にカバーし使用している必要があります

 

#importを<AVFoundation / AVFoundation.h> 
の#import <Masonry.h> 
@interface AVAudioVC()<AVAudioRecorderDelegate> 
@Property(非アトミック強い)* AVAudioRecorder audiorecorder; //音声記録

@property(非アトミック、強い)UIButton * audioRecorderBeginBtn。 //オーディオ録音開始
@property(アトミック、強い)UIButton * audioRecorderPauseBtn; // 一時停止記録
@property(アトミック、強い)UIButton * audioRecorderStopBtn; // ストップ記録オーディオ
、我々はまた、知っている必要があります/ ** AVAudioSessionは、それによって達成することができます:なリミックスなど、オーディオ、およびその他のデータは、多くの場合、以下のこれらのような私たちが遭遇した問題の一部かどうか、電話に応答し、そのようなプラグのヘッドフォンなどのオーディオリソースのAppの現在の状況を、制御するための
 1は、記録または再生していますか?
 
 システムがどのように動作するとき2、ミュートボタンを押しましたか?
 
 3、まだスピーカーから受話器内部から音を再生していますか?
 
 4、どのようにヘッドセットのパフォーマンスを接続するには?
 
 /目覚まし時計が鳴ったパフォーマンスをした後5、どのように呼び出すには?
 
 6、どのように他のオーディオパフォーマンスの後にアプリを起動するには?* / 
@Property * AVAudioSessionセッション(非アトミック、強いです)。
@property(アトミック、強い)AVAudioPlayer *プレイヤー。//播放器 
@end

@implementation AVAudioVC 

- (AVAudioSession *)セッション{ 
    IF(!_セッション){ 
        // AVAudioSession是一个单例实例化
        _SESSION = [AVAudioSession sharedInstance]。
        
        NSError * sessionError。
      
        
        IF(_SESSION == NIL){ 
            
            のNSLog(@ "セッションを作成エラー:%の@"、[sessionError説明])。
            
        }他{ 
            //激活セッション
            [_SESSION用のsetActive:YES誤差:ゼロ]。
            
        } 
    } 
    戻り_SESSION。
} 

- (ボイド)のviewDidLoad { 
    [スーパーのviewDidLoad]。
    【自己setviewコマンド]。
    
    //设备改变
    [NSNotificationCenter defaultCenter] addObserver:自己セレクタ:@selector(handleRouteChange :)名:AVAudioSessionRouteChangeNotificationオブジェクト:[AVAudioSession sharedInstance]; 
    //電流の流れが遮断される
    [[NSNotificationCenter defaultCenter] addObserver:自己セレクタ:@selector(audioInterruption。 )名前:AVAudioSessionInterruptionNotificationオブジェクト:[AVAudioSession sharedInstance]]; 
} 

//ヘッドホンなどを引っ張る
- (ボイド)handleRouteChange:(NSNotification *){をNotI 
    
    NSDictionaryの*情報= noti.userInfo; 
    AVAudioSessionRouteChangeReason理由= [インフォ[AVAudioSessionRouteChangeReasonKey] unsignedIntegerValue]。
    / ** 
     AVAudioSessionRouteChangeReasonUnknown:不明な理由の 
     AVAudioSessionRouteChangeReasonNewDeviceAvailable:新しい機器利用可能
     AVAudioSessionRouteChangeReasonOldDeviceUnavailable:古い機器が使用できません 
     AVAudioSessionRouteChangeReasonCategoryChange:カテゴリは変更されません
     AVAudioSessionRouteChangeReasonOverrideを:設定アプリのリセット出力
     AVAudioSessionRouteChangeReasonWakeFromSleepを:スリープからのウェイクアップは、通話の遷移
     AVAudioSessionRouteChangeReasonNoSuitableRouteForCategoryを:もし適切な装置の現在のカテゴリ
     AVAudioSessionRouteChangeReasonRouteConfigurationChange:ルータの設定の変更
     * / 
    //古いオーディオをデバイス切断
    IF(==理由AVAudioSessionRouteChangeReasonOldDeviceUnavailable){ 
        
        //出力装置の種類の情報の行の記述を取得し、行を取得
        AVAudioSessionRouteDescription * previousRoute =インフォ[AVAudioSessionRouteChangePreviousRouteKey] 。
        * = PreviousRoute.outputs previousOutput AVAudioSessionPortDescription [0]; 
        NSStringの*のportType = previousOutput.portType; 
        
        IF([isEqualToStringとしてのportType:AVAudioSessionPortHeadphones]){ 
             
            //ここで再生を一時停止
        } 
    } 
} 
/ *割り込みオーディオ再生システムモニタ
コール休止
QQマイクロチャネル音声が一時停止し
、他の音楽ソフトウェアが占めます
 * / 
- (無効)audioInterruption:(NSNotification *)のNotI { 
    
    NSDictionaryの*情報= noti.userInfo; 
    タイプ=のAVAudioSessionInterruptionType [情報[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue]; 
    タイプ== AVAudioSessionInterruptionTypeBeganの)IF { 
        //割り込み開始、我々は再生を一時停止すべきですそしてAVAudioSessionInterruptionTypeEndedの取得価額は、私たちがプレーして獲得し続けることができ、中断がオーバーであることを示します。
    }エルス{
        //現在の値AVAudioSessionInterruptionOptionShouldResume一つだけ、この時点では、演奏や収集を継続するために復元する必要があります表します。 
    [audioRecorderView mas_makeConstraints:^(* MASConstraintMakerメイク){
        AVAudioSessionInterruptionOptionsオプション= [インフォ[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue]。
        IF(オプション== AVAudioSessionInterruptionOptionShouldResume){ 
            
        } 
    } 
} 


/ ** 
 所有的控件初始化
 * / 
- (ボイド)setviewコマンド{ 
    
    //音频录制
    のUIView * audioRecorderView = [UIViewの新しいです]。
    audioRecorderView.layer.cornerRadius = 5.0F; 
    audioRecorderView.layer.borderColor = [UIColor blackColor] .CGColor。
    audioRecorderView.layer.borderWidth = 1.0F; 
    [self.viewのaddSubview:audioRecorderView]。
    audioRecorderView.backgroundColor = [UIColor redColor]。
        make.top.offset(90)。
        make.left.offset(12)。
        make.right.offset(-12)。
        make.height.offset(74)。
    }]。
    
    
    
    UILabel * audioRecorderTitleLab = [UILabel新]。
    audioRecorderTitleLab.text = @ "音频录制"。
    [audioRecorderView addSubview:audioRecorderTitleLab]。
    [audioRecorderTitleLab mas_makeConstraints:^(MASConstraintMaker *メイク){ 
        make.left.offset(12)。
        make.height.offset(30)。
    }]。
    
    
    self.audioRecorderBeginBtn = [UIButton buttonWithType:UIButtonTypeCustom]。
    [self.audioRecorderBeginBtnのsetTitle:@ "开始" forState:UIControlStateNormal];
    [self.audioRecorderBeginBtn addTarget:自己アクション:@selector(audioRecorderBeginBtnClick)forControlEvents:UIControlEventTouchUpInside]。
    [audioRecorderView addSubview:self.audioRecorderBeginBtn]。
    [self.audioRecorderBeginBtn mas_makeConstraints:^(MASConstraintMaker *メイク){
        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:自己アクション:@selector(audioRecorderPauseBtnClick)forControlEvents:UIControlEventTouchUpInside]。
    [audioRecorderView addSubview:self.audioRecorderPauseBtn]。
    [self.audioRecorderPauseBtn mas_makeConstraints:^(MASConstraintMaker *メイク){
    [self.audioRecorderStopBtn mas_makeConstraints:^(MASConstraintMaker *メイク){ 
        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:自己アクション:@selector(audioRecorderStopBtnClick)forControlEvents:UIControlEventTouchUpInside]。
    [audioRecorderView addSubview:self.audioRecorderStopBtn]。
        make.left.equalTo(self.audioRecorderPauseBtn.mas_right).offset(12)。
        make.size.equalTo(self.audioRecorderBeginBtn)。
        make.bottom.equalTo(self.audioRecorderBeginBtn.mas_bottom)。
    }]。
    
    
    //音频播放
    
    

} 
/ ** 
 录音开始
 * / 
- (ボイド){audioRecorderBeginBtnClick 
    / ** 
     約2つの初期化方法と同様の二つの方法、構成情報NSDictionaryの
    - (NULL可能instancetype)initWithURL:( NSURL *)URLの設定:(NSDictionaryの<NSStringの*、ID > *)エラーセッティング:(NSError **)をouterror; 
    - (NULL可能instanceType)initWithURL:(NSURL *)形式のURL:(AVAudioFormat *)フォーマットエラー:(NSError **)outerror API_AVAILABLE(MacOSの(10.12)、iOS版(10.0 )、watchos(4.0))API_UNAVAILABLE (tvos)、 
     
     記録を開始する準備ができて
     - (BOOL)prepareToPlay。 
     一時停止録音を
     - (無効)一時停止、
     録音を停止
     - (無効)を停止; 
     
     * / 
    IF(self.audioRecorderBeginBtn.selected){ 
        //すでに始まって
        のNSLog(@「 - -----------------------------記録が開始された、「記録を繰り返す必要はありません); 
       
    }他{ 
        
        / **
         セッションを設定すると、属性
         AVAudioSessionCategoryAmbientを:ユーザがロック画面やミュート、ミュート、サポートミックスは、再生のみサポートしているときとき
         AVAudioSessionCategorySoloAmbient:ミュートは、ミキシングサポートしていないときに、ユーザロック画面やミュートは、再生のみ対応している場合
         AVAudioSessionCategoryPlayback:ときに、ユーザロック画面やミュートミュート時ではない、との混合をサポートしていません、再生のみサポートされてい
         AVAudioSessionCategoryRecord:ときに、ユーザーのロック画面やミュートミュート時ではない、との混合をサポートしていません、唯一のサポート記録
         AVAudioSessionCategoryPlayAndRecord:ユーザーロック画面やミュートがミュートされていない、サポートミックスを、あなたが録音して再生することができます 
        //は開始
        self.audioRecorder = [[ ALLOC] initWithURL AVAudioRecorder:[自己getSavePath ]の設定:[自己getAudioSetting]エラー:なし]。 
         AVAudioSessionCategoryAudioProcessingを:サポートしていません。
         AVAudioSessionCategoryMultiRoute:ロック画面、ユーザが混合サポートしていない場合にミュートまたはミュートでない場合、記録再生をすることができる
         * / 
        [self.sessionのsetCategory:AVAudioSessionCategoryPlayAndRecordエラー:なし];
        
        
        自己= self.audioRecorder.delegate; 
// self.audioRecorder.meteringEnabled = YES; //オープンオーディオ測定
        [self.audioRecorder prepareToRecord]; // 
        [self.audioRecorder録音]; 
        
// 
        [self.audioRecorder updateMeters]; 
        [セルフ.audioRecorder averagePowerForChannel:0]; //指定されたチャネルデシベル値
        [self.audioRecorder peakPowerForChannel:0]; //平均デシベル値
        のNSLog(@「------------------- ------------ @記録が開始された%」、self.audioRecorder); 
    } 
    self.audioRecorderBeginBtn.selected = YES;
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW、(int64_tの)(2 * NSEC_PER_SEC))、dispatch_get_main_queue()、{^ 
         のNSLog(@ "isRecording:1 --------------------- -------------------た:%d」、self.audioRecorder.isRecording); 
    }); 
} 


/ * 
 音频的存储URL 
 * / 
- (NSURL *)getSavePath { 
    NSStringの* urlStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory、NSUserDomainMask、YES)lastObject]。
    urlStr = [urlStr stringByAppendingPathComponent:@ "myRecord.caf"]; 
    NSLog(@ "ファイルパス:%の@"、urlStr)。
    NSURL * URL = [NSURL fileURLWithPath:urlStr]; 
    URLを返します。
} 
/ * 
 @return录音设置
 * / 
- (NSDictionaryの*)getAudioSetting { 
    NSMutableDictionary DICM * = [辞書NSMutableDictionary]; 
    //設定された記録フォーマット
    [DICMのsetObject(kAudioFormatLinearPCM)@ forKey:AVFormatIDKey]。 
    //記録サンプルレートを設定し、レート8000をサンプリングする電話で、平均記録のために十分である
    [DICMのsetObject(8000)forKey @:AVSampleRateKey]; 
    //単一音声チャネルを設定チャネル
    【DICMはのsetObject:@ forKey(1):AVNumberOfChannelsKey]; 
    //各サンプル点のビット数を、8,16,24,32分割
    [@ forKey DICMのsetObjectを(8):AVLinearPCMBitDepthKey]; 
    //使用する場合フローティングサンプリング点
    [DICMのsetObject(YES)forKey @:AVLinearPCMIsFloatKey]; 
    //記録品質
    [DICMのsetObject:[のNSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey]; 
    
    // ...その他の設定は、
    DICMを返す; 
} 


/ ** 
 録音一時停止
 * / 
- (無効){audioRecorderPauseBtnClick 
    IF(!self.audioRecorder){
        返す; 
    } 
 
    IF(self.audioRecorderPauseBtn.selected){
        オーディオ録音開始// 
         [self.audioRecorderレコード]; 
    }他{ 
        //録音音声のポーズ
         [self.audioRecorderのPAUSE]; 
    } 
    self.audioRecorderPauseBtn.selected = self.audioRecorderPauseBtn.selected ;! 
} 


/ ** 
 オーディオ停止を記録
 * / 
- (ボイド)audioRecorderStopBtnClick { 
   
    //まだ記録されている場合
    [self.audioRecorder STOP]; 
    self.audioRecorderBeginBtn.selected = NO; 

} 


の#pragmaマークAVAudioRecorderDelegate 

/ * audioRecorderDidFinishRecording:正常:記録または終了したときに呼び出されます場合は、このメソッドが呼び出されていません。停止レコーダによる中断を停止しています。* /
- (ボイド)audioRecorderDidFinishRecording:(AVAudioRecorder *)レコーダ正常:(BOOL)フラグ{ 
    //录音完成 
    のNSLog(@「--------------:録画が終了します」);
    
// AVAudioPlayer * audioPlayer = [[AVAudioPlayerのalloc] initWithContentsOfURL:[自己getSavePath]エラー:nilを]; 
//もし([audioPlayer prepareToPlay] == YES && 
// [audioPlayer遊ぶ] == YES){ 
//のNSLog(@ "--------------------- -----------:开始播放"); 
//}他{ 
//のNSLog(@ "--------------------------------:失败"); 
//} 

    
} 

/ *エンコードすることがデリゲートに報告される中にエラーが発生した場合。* / 
- (ボイド)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)レコーダーエラー:(NSError * __nullable)エラー{ 
    のNSLog(@ "--------------:录音编码发生错误")。
} 
 * / 
- (ボイド)touchesBegan:(NSSetは<UITouch *> *)withEventタッチ。


/ ** 
 音频播放
    [self.audioRecorder停止]。
    self.player = [[AVAudioPlayer ALLOC] initWithContentsOfURL:[自己getSavePath]エラー:なし]。
//のNSLog(@ "%李"、self.player.data.length / 1024); 
    [self.sessionのsetCategory:AVAudioSessionCategoryPlayback誤差:ゼロ]。
    
    もし([self.player prepareToPlay] == YES && [self.playerプレイ] == YES){ 
        のNSLog(@ "-------------------:播放") ; 
    } {他
         のNSLog(@ "-------------------:停止")。
    } 
  
    
} 


- (ボイド)のdealloc { 
    [NSNotificationCenter defaultCenter] removeObserver:自己]。
} 


@end

 

おすすめ

転載: www.cnblogs.com/hualuoshuijia/p/11512990.html