標籤:blog os strong 檔案 io for art cti
//匯入上面2個架構#import <AVFoundation/AVFoundation.h>#import <CoreFoundation/CoreFoundation.h>//聲明下面4個屬性@property (nonatomic ,assign)BOOL recording; //判斷是否可以錄製@property (nonatomic ,strong)NSString *fileName; //音頻檔案儲存體時的檔案名稱@property (nonatomic ,strong)AVAudioRecorder *recorder; //聲明一個錄製器@property (nonatomic ,strong)AVAudioPlayer *player; //聲明一個音頻播放器- (void)startRecording{if (self.recording) { return; } self.recording =YES;// 設定錄音格式 AVFormatIDKey==kAudioFormatLinearPCM// 設定錄音採樣率(Hz) 如:AVSampleRateKey==8000/44100/96000(影響音訊品質)// 錄音通道數 1 或 2 AVNumberOfChannelsKey// 線性採樣位元 8、16、24、32 AVLinearPCMBitDepthKey// 錄音的品質 AVEncoderAudioQualityKey == AVAudioQualityHigh// AVLinearPCMIsBigEndianKey 大端還是小端,是記憶體的組織方式// AVLinearPCMIsFloatKey 採樣訊號是整數還是浮點數 NSDictionary *audioSettingDict =[NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithFloat:8000],AVSampleRateKey, [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey, [NSNumber numberWithInt:1],AVNumberOfChannelsKey, [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey, [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey, [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey, [NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey, nil]; NSError *error =nil; AVAudioSession * audioSession = [AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];//設定音頻類別,這裡表示當應用啟動,停掉後台其他音頻 [audioSession setActive:YES error:&error];//設定當前應用音頻活躍性 NSDate *now =[NSDate date]; //執行個體化一個NSDateFormatter對象 NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init]; //設定時間格式,這裡可以設定成自己需要的格式 [dateFormater setDateFormat:@"yyyy-MM-dd HH-mm-ss"]; NSString *fileName = [NSString stringWithFormat:@"rec_%@.wav",[dateFormater stringFromDate:now]]; self.fileName =fileName; NSString *filePath =[NSString documentPathWith:fileName]; NSURL *fileUrl =[NSURL URLWithString:filePath]; // 初始化錄製的類 self.recorder =[[AVAudioRecorder alloc]initWithURL:fileUrl settings:audioSettingDict error:&error]; [self.recorder prepareToRecord]; [self.recorder peakPowerForChannel:0]; [self.recorder setMeteringEnabled:YES]; [self.recorder record];}