iOS使用音频处理框架The Amazing Audio Engine实现音频录制播放

iOS使用音频处理框架The Amazing Audio Engine实现音频录制播放,第1张

概述iOS使用音频处理框架The Amazing Audio Engine实现音频录制播放 iOS 第三方音频框架The Amazing Audio Engine使用,实现音频录制.播放,可设置配乐. 首先看一下效果图: 下面贴上核心控制器代码: #import "ViewController.h" #import <AVFoundation/AVFoundation.h> #import "HWProgressHUD.h" #import "UIImage+HW.h" #import "AERecord ...

iOS 第三方音频框架The Amazing Audio Engine使用,实现音频录制、播放,可设置配乐。

首先看一下效果图:


下面贴上核心控制器代码:

#import "VIEwController.h"#import <AVFoundation/AVFoundation.h>#import "HWProgressHUD.h"#import "UIImage+HW.h"#import "AERecorder.h"#import "HWRecordingDrawVIEw.h"#define KMainW [UIScreen mainScreen].bounds.size.wIDth#define KMainH [UIScreen mainScreen].bounds.size.height@interface VIEwController ()@property (nonatomic,strong) AERecorder *recorder;@property (nonatomic,strong) AEAudioController *audioController;@property (nonatomic,strong) AEAudiofilePlayer *player;@property (nonatomic,strong) AEAudiofilePlayer *backgroundplayer;@property (nonatomic,strong) NSTimer *timer;@property (nonatomic,strong) NSMutableArray *soundSource;@property (nonatomic,weak) HWRecordingDrawVIEw *recordingDrawVIEw;@property (nonatomic,weak) UILabel *recLabel;@property (nonatomic,weak) UILabel *recordTimeLabel;@property (nonatomic,weak) UILabel *playTimeLabel;@property (nonatomic,weak) UIbutton *auditionBtn;@property (nonatomic,weak) UIbutton *recordBtn;@property (nonatomic,weak) UiSlider *slIDer;@property (nonatomic,copy) Nsstring *path;@end@implementation VIEwController- (AEAudioController *)audioController{ if (!_audioController) { _audioController = [[AEAudioController alloc] initWithAudioDescription:[AEAudioController nonInterleavedfloatStereoAudioDescription] inputEnabled:YES]; _audioController.preferredBufferDuration = 0.005; _audioController.useMeasurementMode = YES; } return _audioController;}- (NSMutableArray *)soundSource{ if (!_soundSource) { _soundSource = [NSMutableArray array]; } return _soundSource;}- (voID)vIEwDIDLoad { [super vIEwDIDLoad]; [self creatControl];}- (voID)creatControl{ CGfloat marginX = 30.0f; //音频视图 HWRecordingDrawVIEw *recordingDrawVIEw = [[HWRecordingDrawVIEw alloc] initWithFrame:CGRectMake(marginX,80,KMainW - marginX * 2,100)]; [self.vIEw addSubvIEw:recordingDrawVIEw]; _recordingDrawVIEw = recordingDrawVIEw; //REC UILabel *recLabel = [[UILabel alloc] initWithFrame:CGRectMake(marginX,CGRectGetMaxY(recordingDrawVIEw.frame) + 20,40)]; recLabel.text = @"REC"; recLabel.textcolor = [UIcolor redcolor]; [self.vIEw addSubvIEw:recLabel]; _recLabel = recLabel; //录制时间 UILabel *recordTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(recLabel.frame) + 20,CGRectGetMinY(recLabel.frame),150,40)]; recordTimeLabel.text = @"录制时长:00:00"; [self.vIEw addSubvIEw:recordTimeLabel]; _recordTimeLabel = recordTimeLabel; //播放时间 UILabel *playTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(recordTimeLabel.frame),CGRectGetMaxY(recordTimeLabel.frame),40)]; playTimeLabel.text = @"播放时长:00:00"; playTimeLabel.hIDden = YES; [self.vIEw addSubvIEw:playTimeLabel]; _playTimeLabel = playTimeLabel; //配乐按钮 NSArray *TitleArray = @[@"无配乐",@"夏天",@"阳光海湾"]; CGfloat btnW = 80.0f; CGfloat padding = (KMainW - marginX * 2 - btnW * TitleArray.count) / (TitleArray.count - 1); for (int i = 0; i < TitleArray.count; i++) { CGfloat btnX = marginX + (btnW + padding) * i; UIbutton *btn = [[UIbutton alloc] initWithFrame:CGRectMake(btnX,CGRectGetMaxY(playTimeLabel.frame) + 20,btnW,btnW)]; [btn setTitle:TitleArray[i] forState:UIControlStatenormal]; btn.layer.cornerRadius = btnW * 0.5; btn.layer.masksToBounds = YES; [btn setBackgroundImage:[UIImage imageWithcolor:[UIcolor graycolor]] forState:UIControlStatenormal]; [btn setBackgroundImage:[UIImage imageWithcolor:[UIcolor orangecolor]] forState:UIControlStateSelected]; if (i == 0) btn.selected = YES; btn.tag = 100 + i; [btn addTarget:self action:@selector(changeBackgroundMusic:) forControlEvents:UIControlEventtouchUpInsIDe]; [self.vIEw addSubvIEw:btn]; } //配乐音量 UILabel *backgroundLabel = [[UILabel alloc] initWithFrame:CGRectMake(marginX + 10,CGRectGetMaxY(playTimeLabel.frame) + 120,40)]; backgroundLabel.text = @"配乐音量"; [self.vIEw addSubvIEw:backgroundLabel]; //配乐音量 UiSlider *slIDer = [[UiSlider alloc] initWithFrame:CGRectMake(CGRectGetMaxX(backgroundLabel.frame) + 10,CGRectGetMinY(backgroundLabel.frame),210,40)]; slIDer.value = 0.4f; [slIDer addTarget:self action:@selector(slIDerValueChanged:) forControlEvents:UIControlEventValueChanged]; [self.vIEw addSubvIEw:slIDer]; _slIDer = slIDer; //试听按钮 UIbutton *auditionBtn = [[UIbutton alloc] initWithFrame:CGRectMake(marginX,KMainH - 150,120,80)]; auditionBtn.hIDden = YES; auditionBtn.backgroundcolor = [UIcolor blackcolor]; [auditionBtn setTitle:@"试听" forState:UIControlStatenormal]; [auditionBtn setTitle:@"停止" forState:UIControlStateSelected]; [auditionBtn addTarget:self action:@selector(auditionBtnOnClick:) forControlEvents:UIControlEventtouchUpInsIDe]; [self.vIEw addSubvIEw:auditionBtn]; _auditionBtn = auditionBtn; //录音按钮 UIbutton *recordBtn = [[UIbutton alloc] initWithFrame:CGRectMake(KMainW - marginX - 120,80)]; recordBtn.backgroundcolor = [UIcolor blackcolor]; [recordBtn setTitle:@"开始" forState:UIControlStatenormal]; [recordBtn setTitle:@"暂停" forState:UIControlStateSelected]; [recordBtn addTarget:self action:@selector(recordBtnOnClick:) forControlEvents:UIControlEventtouchUpInsIDe]; [self.vIEw addSubvIEw:recordBtn]; _recordBtn = recordBtn;}//配乐按钮点击事件- (voID)changeBackgroundMusic:(UIbutton *)btn{ //更新选中状态 for (int i = 0; i < 3; i++) { UIbutton *button = (UIbutton *)[self.vIEw vIEwWithTag:100 + i]; button.selected = NO; } btn.selected = YES; //移除之前配乐 if (_backgroundplayer) { [_audioController removeChannels:@[_backgroundplayer]]; _backgroundplayer = nil; } NSURL *url; if (btn.tag == 100) { return; }else if (btn.tag == 101) { url = [[NSBundle mainBundle]URLForResource:@"夏天.mp3" withExtension:nil]; }else if (btn.tag == 102) { url = [[NSBundle mainBundle]URLForResource:@"阳光海湾.mp3" withExtension:nil]; } [self.audioController start:NulL]; NSError *AVerror = NulL; _backgroundplayer = [AEAudiofilePlayer audiofilePlayerWithURL:url error:&AVerror]; _backgroundplayer.volume = _slIDer.value; _backgroundplayer.loop = YES; if (!_backgroundplayer) { [[[UIAlertVIEw alloc] initWithTitle:@"Error"     message:[Nsstring stringWithFormat:@"Couldn't start playback: %@",[AVerror localizedDescription]]     delegate:nil    cancelbuttonTitle:nil    otherbuttonTitles:@"OK",nil] show]; return; } //放完移除 _backgroundplayer.removeUponFinish = YES; __weak VIEwController *weakSelf = self; _backgroundplayer.completionBlock = ^{ weakSelf.backgroundplayer = nil; }; [_audioController addChannels:@[_backgroundplayer]];}//配乐音量slIDer滑动事件- (voID)slIDerValueChanged:(UiSlider *)slIDer{ if (_backgroundplayer) _backgroundplayer.volume = slIDer.value;}//录音按钮点击事件- (voID)recordBtnOnClick:(UIbutton *)btn{ [[AVAudioSession sharedInstance] requestRecordPermission:^(BOol granted) { if (granted) {  //用户同意获取麦克风  dispatch_after(dispatch_time(disPATCH_TIME_Now,(int64_t)(.1f * NSEC_PER_SEC)),dispatch_get_main_queue(),^{  btn.selected = !btn.selected;  if (btn.selected) {   [self startRecord];  }else {   [self finishRecord];  }  }); }else {  //用户不同意获取麦克风  [HWProgressHUD showMessage:@"需要访问您的麦克风,请在“设置-隐私-麦克风”中允许访问。" duration:3.f]; } }];}//开始录音- (voID)startRecord{ _auditionBtn.hIDden = YES; [self.audioController start:NulL]; _recorder = [[AERecorder alloc] initWithAudioController:_audioController]; _path = [self getPath]; NSError *error = NulL; if ( ![_recorder beginRecordingTofileAtPath:_path fileType:kAudiofileM4AType error:&error] ) { [[[UIAlertVIEw alloc] initWithTitle:@"Error" message:[Nsstring stringWithFormat:@"Couldn't start recording: %@",[error localizedDescription]] delegate:nil cancelbuttonTitle:nil otherbuttonTitles:@"OK",nil] show]; _recorder = nil; return; } [self.soundSource removeAllObjects]; [self removeTimer]; [self addRecordTimer]; [_audioController addOutputReceiver:_recorder]; [_audioController addinputReceiver:_recorder];}//结束录音- (voID)finishRecord{ _auditionBtn.hIDden = NO; _recLabel.hIDden = NO; [self removeTimer]; [_recorder finishRecording]; [_audioController removeOutputReceiver:_recorder]; [_audioController removeinputReceiver:_recorder]; _recorder = nil;}//添加录音定时器- (voID)addRecordTimer{ self.timer = [NSTimer scheduledTimerWithTimeInterval:.2f target:self selector:@selector(recordTimerAction) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];}//录音定时器事件- (voID)recordTimerAction{ //获取音频 [CATransaction begin]; [CATransaction setdisableActions:YES]; float32 inputAvg,inputPeak,outputAvg,outputPeak; [_audioController inputAveragePowerLevel:&inputAvg peakHoldLevel:&inputPeak]; [_audioController outputAveragePowerLevel:&outputAvg peakHoldLevel:&outputPeak]; [self.soundSource insertObject:[NSNumber numberWithfloat:(inputPeak + 18) * 2.8] atIndex:0]; [CATransaction commit]; _recordingDrawVIEw.pointArray = _soundSource; //REC闪动 _recLabel.hIDden = (int)[self.recorder currentTime] % 2 == 1 ? YES : NO; //录音时间 Nsstring *str = [self strWithTime:[self.recorder currentTime] interval:0.5f]; if ([str intValue] < 0) str = @"录制时长:00:00"; [self.recordTimeLabel setText:[Nsstring stringWithFormat:@"录制时长:%@",str]];}//移除定时器- (voID)removeTimer{ [self.timer invalIDate]; self.timer = nil;}//试听按钮点击事件- (voID)auditionBtnOnClick:(UIbutton *)btn{ btn.selected = !btn.selected; if (btn.selected) { [self playRecord]; }else { [self stopPlayRecord]; }}//播放录音- (voID)playRecord{ //更新界面 _recordBtn.hIDden = YES; [_playTimeLabel setText:@"播放时长:00:00"]; _playTimeLabel.hIDden = NO; //取消背景音乐 [self changeBackgroundMusic:(UIbutton *)[self.vIEw vIEwWithTag:100]]; if (![[NSfileManager defaultManager] fileExistsAtPath:_path]) return; NSError *error = nil; _player = [AEAudiofilePlayer audiofilePlayerWithURL:[NSURL fileURLWithPath:_path] error:&error]; if (!_player) { [[[UIAlertVIEw alloc] initWithTitle:@"Error"     message:[Nsstring stringWithFormat:@"Couldn't start playback: %@",[error localizedDescription]]     delegate:nil    cancelbuttonTitle:nil    otherbuttonTitles:@"OK",nil] show]; return; } [self addplayTimer]; _player.removeUponFinish = YES; __weak VIEwController *weakSelf = self; _player.completionBlock = ^{ weakSelf.player = nil; weakSelf.auditionBtn.selected = NO; [weakSelf stopPlayRecord]; }; [self.audioController start:NulL]; [self.audioController addChannels:@[_player]];}//停止播放录音- (voID)stopPlayRecord{ _recordBtn.hIDden = NO; _playTimeLabel.hIDden = YES; [self removeTimer]; if (_player) [_audioController removeChannels:@[_player]];}//添加播放定时器- (voID)addplayTimer{ self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(playTimerAction) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];}//播放定时器事件- (voID)playTimerAction{ //播放时间 Nsstring *str = [self strWithTime:[_player currentTime] interval:1.f]; if ([str intValue] < 0) str = @"播放时长:00:00"; [_playTimeLabel setText:[Nsstring stringWithFormat:@"播放时长:%@",str]];}//录制音频沙盒路径- (Nsstring *)getPath{ NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"YYYYMMddhhmmss"]; Nsstring *recordname = [Nsstring stringWithFormat:@"%@.wav",[formatter stringFromDate:[NSDate date]]]; Nsstring *path = [[NSSearchPathForDirectorIEsInDomains(NSdocumentDirectory,NSUserDomainMask,YES) lastObject] stringByAppendingPathComponent:recordname]; return path;}//时长长度转时间字符串- (Nsstring *)strWithTime:(double)time interval:(CGfloat)interval{ int minute = (time * interval) / 60; int second = (int)(time * interval) % 60; return [Nsstring stringWithFormat:@"%02d:%02d",minute,second];}@end

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

总结

以上是内存溢出为你收集整理的iOS使用音频处理框架The Amazing Audio Engine实现音频录制播放全部内容,希望文章能够帮你解决iOS使用音频处理框架The Amazing Audio Engine实现音频录制播放所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1108001.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存