我的编程空间,编程开发者的网络收藏夹
学习永远不晚

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

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

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 "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, 80, 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), 150, 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, 80, 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, KMainH - 150, 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

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

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

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

下载Word文档到电脑,方便收藏和打印~

下载Word文档

编程热搜

  • Android:VolumeShaper
    VolumeShaper(支持版本改一下,minsdkversion:26,android8.0(api26)进一步学习对声音的编辑,可以让音频的声音有变化的播放 VolumeShaper.Configuration的三个参数 durati
    Android:VolumeShaper
  • Android崩溃异常捕获方法
    开发中最让人头疼的是应用突然爆炸,然后跳回到桌面。而且我们常常不知道这种状况会何时出现,在应用调试阶段还好,还可以通过调试工具的日志查看错误出现在哪里。但平时使用的时候给你闹崩溃,那你就欲哭无泪了。 那么今天主要讲一下如何去捕捉系统出现的U
    Android崩溃异常捕获方法
  • android开发教程之获取power_profile.xml文件的方法(android运行时能耗值)
    系统的设置–>电池–>使用情况中,统计的能耗的使用情况也是以power_profile.xml的value作为基础参数的1、我的手机中power_profile.xml的内容: HTC t328w代码如下:
    android开发教程之获取power_profile.xml文件的方法(android运行时能耗值)
  • Android SQLite数据库基本操作方法
    程序的最主要的功能在于对数据进行操作,通过对数据进行操作来实现某个功能。而数据库就是很重要的一个方面的,Android中内置了小巧轻便,功能却很强的一个数据库–SQLite数据库。那么就来看一下在Android程序中怎么去操作SQLite数
    Android SQLite数据库基本操作方法
  • ubuntu21.04怎么创建桌面快捷图标?ubuntu软件放到桌面的技巧
    工作的时候为了方便直接打开编辑文件,一些常用的软件或者文件我们会放在桌面,但是在ubuntu20.04下直接直接拖拽文件到桌面根本没有效果,在进入桌面后发现软件列表中的软件只能收藏到面板,无法复制到桌面使用,不知道为什么会这样,似乎并不是很
    ubuntu21.04怎么创建桌面快捷图标?ubuntu软件放到桌面的技巧
  • android获取当前手机号示例程序
    代码如下: public String getLocalNumber() { TelephonyManager tManager =
    android获取当前手机号示例程序
  • Android音视频开发(三)TextureView
    简介 TextureView与SurfaceView类似,可用于显示视频或OpenGL场景。 与SurfaceView的区别 SurfaceView不能使用变换和缩放等操作,不能叠加(Overlay)两个SurfaceView。 Textu
    Android音视频开发(三)TextureView
  • android获取屏幕高度和宽度的实现方法
    本文实例讲述了android获取屏幕高度和宽度的实现方法。分享给大家供大家参考。具体分析如下: 我们需要获取Android手机或Pad的屏幕的物理尺寸,以便于界面的设计或是其他功能的实现。下面就介绍讲一讲如何获取屏幕的物理尺寸 下面的代码即
    android获取屏幕高度和宽度的实现方法
  • Android自定义popupwindow实例代码
    先来看看效果图:一、布局
  • Android第一次实验
    一、实验原理 1.1实验目标 编程实现用户名与密码的存储与调用。 1.2实验要求 设计用户登录界面、登录成功界面、用户注册界面,用户注册时,将其用户名、密码保存到SharedPreference中,登录时输入用户名、密码,读取SharedP
    Android第一次实验

目录