首先一定記得權限
Privacy - Microphone Usage Description
然后先看一下界面
這是三個button
導入庫AVFoundation
以及代碼實現部分
#import <上述庫的頭文件>
# define COUNTDOWN 60
全局變量
{
NSTimer *_timer; //定時器
NSInteger countDown;? //倒計時
NSString *filePath;
}
第一個按鈕方法
NSLog(@"開始錄音");
AVAudioSession *session =[AVAudioSession sharedInstance];
NSError *sessionError;
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
if (session == nil) {
NSLog(@"Error creating session: %@",[sessionError description]);
}else{
[session setActive:YES error:nil];
}
self.session = session;
//1.獲取沙盒地址
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
filePath = [path stringByAppendingString:@"/RRecord.wav"];
//2.獲取文件路徑
self.recordFileUrl = [NSURL fileURLWithPath:filePath];
//設置參數
NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
//采樣率? 8000/11025/22050/44100/96000(影響音頻的質量)
[NSNumber numberWithFloat: 8000.0],AVSampleRateKey,
// 音頻格式
[NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
//采樣位數? 8、16、24、32 默認為16
[NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
// 音頻通道數 1 或 2
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
//錄音質量
[NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,
nil];
_recorder = [[AVAudioRecorder alloc] initWithURL:self.recordFileUrl settings:recordSetting error:nil];
if (_recorder) {
_recorder.meteringEnabled = YES;
[_recorder prepareToRecord];
[_recorder record];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self stopRecord:nil];
});
}else{
NSLog(@"音頻格式和文件存儲格式不匹配,無法初始化Recorder");
}
第二個按鈕方法
NSLog(@"停止錄音");
if ([self.recorder isRecording]) {
[self.recorder stop];
}
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
_noticeLabel.text = [NSString stringWithFormat:@"錄了 %ld 秒,文件大小為 %.2fKb",COUNTDOWN - (long)countDown,[[manager attributesOfItemAtPath:filePath error:nil] fileSize]/1024.0];
}else{
_noticeLabel.text = @"最多錄60秒";
}
最后一個方法
NSLog(@"播放錄音");
[self.recorder stop];
if ([self.player isPlaying])return;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.recordFileUrl error:nil];
NSLog(@"%li",self.player.data.length/1024);
[self.session setCategory:AVAudioSessionCategoryPlayback error:nil];
[self.player play];