参考资料:
[简书地址](http://www.jianshu.com/users/23d0ae412e19/latest_articles)
#import <UIKit/UIKit.h>
@interface RecordingHub : UIView
@property (nonatomic,assign) float peakPower;
// 按下
- (void)recordButtonTouchDown;
// 移动到外面
- (void)recordButtonTouchUpOutside;
@end
#import "RecordingHub.h"
@interface RecordingHub()
@property (nonatomic,strong) UIView *bgView;
@property (nonatomic,strong) UIImageView *recordVoiceView;
@property (nonatomic,strong) UILabel *textLabel; // 显示文字
@property (nonatomic,strong) NSTimer *timer;
@end
/**
* Description: 麦克风弹出窗口
*/
@implementation RecordingHub
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self setUpUI];
}
return self;
}
- (void)setUpUI{
// 背景
_bgView = [[UIView alloc]initWithFrame:self.bounds];
_bgView.backgroundColor = [UIColor grayColor];
_bgView.layer.cornerRadius = 6;
_bgView.layer.masksToBounds= true;
_bgView.alpha = 0.5;
[self addSubview:_bgView];
// 麦克风
_recordVoiceView = [[UIImageView alloc]init];
_recordVoiceView.frame = CGRectMake(10, 0, self.bounds.size.width - 20, self.bounds.size.height - 10);
_recordVoiceView.image = [UIImage imageNamed:@"VoiceSearchFeedback001"];
[self addSubview:_recordVoiceView];
// 文字
_textLabel = [[UILabel alloc]init];
_textLabel.frame = CGRectMake(5,self.bounds.size.height - 30,self.bounds.size.width - 10,25);
_textLabel.textAlignment = NSTextAlignmentCenter;
_textLabel.textColor = [UIColor whiteColor];
_textLabel.backgroundColor = [UIColor clearColor];
_textLabel.text = @"请说话.....";
_textLabel.font = [UIFont systemFontOfSize:12];
_textLabel.layer.cornerRadius = 6;
_textLabel.layer.masksToBounds = YES;
_textLabel.layer.borderColor = [[UIColor redColor] colorWithAlphaComponent:0.5].CGColor;
[self addSubview:_textLabel];
}
// 按下
- (void)recordButtonTouchDown{
_textLabel.text = @"松开发送";
_textLabel.backgroundColor = [UIColor clearColor];
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateVoiceImage) userInfo:nil repeats:YES];
[[UIApplication sharedApplication].keyWindow addSubview:self];
}
// 移动到外面
- (void)recordButtonTouchUpOutside{
[_timer invalidate];
[self removeFromSuperview];
}
// 改变图片的状态变化
- (void)updateVoiceImage{
_recordVoiceView.image = [UIImage imageNamed:@"VoiceSearchFeedback001@2x"];
float number = fabs(_peakPower);
NSLog(@"number is --->%f",number);
if (10< number && number< 20) {
[_recordVoiceView setImage:[UIImage imageNamed:@"VoiceSearchFeedback001@2x"]];
}else if (20<number && number<=30) {
[_recordVoiceView setImage:[UIImage imageNamed:@"VoiceSearchFeedback002@2x"]];
}else if (30<number && number<=40) {
[_recordVoiceView setImage:[UIImage imageNamed:@"VoiceSearchFeedback003@2x"]];
}else if (40<number && number<=50) {
[_recordVoiceView setImage:[UIImage imageNamed:@"VoiceSearchFeedback004@2x"]];
}else if (50<number && number<=60) {
[_recordVoiceView setImage:[UIImage imageNamed:@"VoiceSearchFeedback005@2x"]];
}else if (60<number && number<=70) {
[_recordVoiceView setImage:[UIImage imageNamed:@"VoiceSearchFeedback006@2x"]];
}else if (70<number && number<=80) {
[_recordVoiceView setImage:[UIImage imageNamed:@"VoiceSearchFeedback007@2x"]];
}else if (80<number && number<=90) {
[_recordVoiceView setImage:[UIImage imageNamed:@"VoiceSearchFeedback008@2x"]];
}else if (90<number && number<=100) {
[_recordVoiceView setImage:[UIImage imageNamed:@"VoiceSearchFeedback009@2x"]];
}else {
[_recordVoiceView setImage:[UIImage imageNamed:@"VoiceSearchFeedback020@2x"]];
}
}
@end
#import "ViewController.h"
#import "RecordingHub.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *voiderBtn;
@property (nonatomic,strong) RecordingHub *hud;
@property (nonatomic,strong) AVAudioRecorder *recorder;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,strong) NSURL *recordedFile;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 设置好文件的存储位置
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [pathArray lastObject];
path = [path stringByAppendingPathComponent:@"RecordedFile"];
bool existsFlag = [manager fileExistsAtPath:path];
if (!existsFlag) {
bool isSuccess = [manager createFileAtPath:path contents:nil attributes:nil];
if (isSuccess) {
NSLog(@"创建成功");
}else{
NSLog(@"创建失败");
}
}
_recordedFile = [NSURL fileURLWithPath:path];
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error;
// 开启录音和播放功能
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
if (session == nil) {
NSLog(@"session is error ---->%@",error.description);
}else{
[session setActive:true error:nil];
}
_hud = [[RecordingHub alloc]initWithFrame:CGRectMake(self.view.bounds.size.width/2-100/2, self.view.bounds.size.height/2, 100, 100)];
[_voiderBtn addTarget:self action:@selector(touchDown:) forControlEvents:UIControlEventTouchDown];
[_voiderBtn addTarget:self action:@selector(touchOutside:) forControlEvents:UIControlEventTouchUpInside];
}
// 按下的时候
- (void)touchDown:(UIButton *)btn{
[_hud recordButtonTouchDown];
NSMutableDictionary * recordSetting = [NSMutableDictionary dictionary];
//设置录音格式
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
//设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量)
[recordSetting setValue:[NSNumber numberWithFloat:16000.0] forKey:AVSampleRateKey];
//录音通道数 1 或 2
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
// 初始化录音
_recorder = [[AVAudioRecorder alloc]initWithURL:_recordedFile settings:recordSetting error:nil];
// 准备录音
[_recorder prepareToRecord];
//开启音量检测
_recorder.meteringEnabled = YES;
// 开始录音
[_recorder record];
NSLog(@"开始录音.....");
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeVoider) userInfo:nil repeats:YES];
}
// 抬起来的时候
- (void)touchOutside:(UIButton *)btn{
[_hud recordButtonTouchUpOutside];
[_timer invalidate];
}
// 声音变化
- (void)changeVoider{
float peakPower = [_recorder averagePowerForChannel:0];
NSLog(@"声音的变化--->%f",peakPower);
[_recorder updateMeters];
_hud.peakPower = peakPower;
}
@end
效果如下: