#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<AVAudioRecorderDelegate>
@property (nonatomic, strong) AVAudioRecorder *audioRecorder;//音频录音机
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;//音频播放用
@property (nonatomic, strong) NSTimer *timer;
@property (weak, nonatomic) IBOutlet UIProgressView *audioPower;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self setAudioSession];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//设置音频会话
- (void)setAudioSession {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//设置为播放和录音状态,以便在录制完之后播放录音
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];
}
//设置录音保存路径
- (NSURL *)getSavePath {
NSString *urlStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
urlStr = [urlStr stringByAppendingPathComponent:@"myrecord.caf"];
NSURL *url = [NSURL fileURLWithPath:urlStr];
return url;
}
//取得录音文件的设置
- (NSDictionary *)getAudioSetting {
NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
//设置录音格式
[dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
//设置录音采样率,8000是电话采样率,对于一般录音已经够用了
[dicM setObject:@(8000) forKey:AVSampleRateKey];
//设置通道,这里采用单声道
[dicM setObject:@(1) forKey:AVNumberOfChannelsKey];
//每个采样点位数,分为8,16,24,32
[dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];
//是否使用浮点数采样
[dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
//...其他设置等
return dicM;
}
#pragma mark 懒加载
//创建录音机
- (AVAudioRecorder *)audioRecorder {
if (!_audioRecorder) {
//创建录音文件保存路径
NSURL *url = [self getSavePath];
//创建录音格式设置
NSDictionary *setting = [self getAudioSetting];
//创建录音机
NSError *error = nil;
_audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:setting error:&error];
_audioRecorder.delegate = self;
_audioRecorder.meteringEnabled = YES;//如果要监控声波必须要设置为yes
if (error) {
NSLog(@"创建录音机对象时发生错误");
return nil;
}
}
return _audioRecorder;
}
//创建播放器
- (AVAudioPlayer *)audioPlayer {
if (!_audioPlayer) {
//创建播放路径
NSURL *url = [self getSavePath];
//创建播放器
NSError *error = nil;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
_audioPlayer.numberOfLoops = 0;
[_audioPlayer prepareToPlay];
if (error) {
NSLog(@"创建播放器过程中发生错误");
return nil;
}
}
return _audioPlayer;
}
#pragma mark 录音声波监控定制器
- (NSTimer *)timer {
if (!_timer) {
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(audioPowerChange) userInfo:nil repeats:YES];
}
return _timer;
}
- (void)audioPowerChange {
[self.audioRecorder updateMeters];//更新测量值
CGFloat power = [self.audioRecorder averagePowerForChannel:0];//取得第一个通道的音频,注意音频强度范围为-160到0之间
CGFloat progress = (1.0/160) * (power + 160.0);
[self.audioPower setProgress:progress ];
}
//开始录音
- (IBAction)start:(id)sender {
//在指定的时长开始录音并设置时长
BOOL result = [self.audioRecorder recordAtTime:0.0 forDuration:10.0];
if (result) {
NSLog(@"设置了录音时长是10s");
if (![self.audioRecorder isRecording]) {
[self.audioRecorder record];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风
self.timer.fireDate = [NSDate distantPast];
}
}
}
//暂停
- (IBAction)pause:(id)sender {
if (![self.audioRecorder isRecording]) {
[self.audioRecorder pause];
self.timer.fireDate = [NSDate distantFuture];
}
}
/**
* 点击恢复按钮
* 恢复录音只需要再次调用record,AVAudioSession会帮助你记录上次录音位置并追加录音
*
* @param sender 恢复按钮
*/
- (IBAction)resume:(id)sender {
[self start:sender];
}
//停止
- (IBAction)stop:(id)sender {
[self.audioRecorder stop];
self.timer.fireDate = [NSDate distantFuture];
self.audioPower.progress = 0.0;
}
#pragma mark 录音完成后实现的代理方法
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
if (![self.audioPlayer isPlaying]) {
[self.audioPlayer play];
}
NSLog(@"录音完成");
NSLog(@"%@",NSHomeDirectory());
}