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

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

(0)

相关推荐

  • 解决ios微信下vue项目组件切换并自动播放音频问题

    最近在做一个英语答题项目 , 项目需求是通过答题取的成绩 , 答题的题型是分为 , 听音选图 , 看图选词 , 和填空题 . 项目总共分为了3个页面 , 开始页 ,答题页 和结束页面 ,答题页关于每种题型 , 我做了相应的组件 , 每次切换题目的时候 ,显示对应的的组件 , 要求听音选图的时候会自动播放音频 . 惯例 , ios下的safari和微信内置浏览器都不支持audio的自动播放 , 通常的解决方案都是通过 document.addEventListener('WeixinJSBridg

  • iOS开发实现音频播放功能

    音频播放 1.介绍 - 功能介绍 用于播放比较长的音频.说明.音乐 ,使用到的是AVFoundation - 框架介绍 * AVAudioPlayer * 初始化: 注意 : (3)必须声明全局变量的音乐播放对象.或者是属性的音乐播放对象  才可以播放 (4)在退出播放页面的时候 一定要把播放对象置空  同时把delegate置空 导入框架:#import <AVFoundation/AVFoundation.h> 声明全局变量 @interface ViewController ()<

  • 详解iOS应用中播放本地视频以及选取本地音频的组件用法

    MPMoviePlayerControlle播放本地视频 MPMoviePlayerControlle与AVAudioPlayer有点类似,前者播放视频,后者播放音频,不过也有很大不同,MPMoviePlayerController 可以直接通过远程URL初始化,而AVAudioPlayer则不可以.不过大体上用起来感觉差不多.废话少说进入体验. 格式支持:MOV.MP4.M4V.与3GP等格式,还支持多种音频格式. 首先你得引入 MediaPlayer.framework.然后在使用到MPMo

  • iOS中的音频服务和音频AVAudioPlayer音频播放器使用指南

    AudioServicesPlaySystemSound音频服务 对于简单的.无混音音频,AVAudio ToolBox框架提供了一个简单的C语言风格的音频服务.你可以使用AudioservicesPlaySystemSound函数来播放简单的声音.要遵守以下几个规则: 1.音频长度小于30秒 2.格式只能是PCM或者IMA4 3.文件必须被存储为.caf..aif.或者.wav格式 4.简单音频不能从内存播放,而只能是磁盘文件 除了对简单音频的限制外,你对于音频播放的方式也基本无法控制.一旦音

  • IOS中微信小程序播放缓存的音频文件的方法

    很多时候我们都想把数据预先缓存到本地,节省带宽.但是最近在处理微信小程序播放缓存到本地的音频文件的时候,遇到一些小问题,然后对于安卓和IOS需要采用不同的播放策略. 首先,如果哪怕用audio标签来播放在线的音频文件,假如服务端没有实现断点续传,IOS是无法播放的,这个需要注意. 对于缓存在小程序的音频(wx.saveFile(OBJECT)保存的音频),IOS只能通过播放背景音乐的接口播放,其它播放方法都没有成功实践,而对于安卓,内部 audio 上下文 innerAudioContext 对

  • 详解iOS App中调用AVAudioPlayer播放音频文件的用法

    要给工程中添加音频,首先要导入音频的框架 AVFoundation.framework 然后新建一个类继承于UIViewController, 我这里就叫FirstVC. 首先在 AppDelegate.m中初始化根视图 复制代码 代码如下: #import "AppDelegate.h" #import "FirstVC.h" @implementation AppDelegate - (void)dealloc {     [_window release];

  • 小程序ios音频播放没声音问题的解决

    小程序提供了录音和播放音频的能力,从基础库 1.6.0 开始支持了wx.getRecorderManager(),录音都采用wx.getRecorderManager()提供的api,播放音频文件采用wx.createInnerAudioContext()提供的api 导入录音和播放音频功能 const recorderManager = wx.getRecorderManager(); // 录音功能 const innerAudioContext = wx.createInnerAudioC

  • iOS开发中音频工具类的封装以及音乐播放器的细节控制

    一.控制器间数据传递 两个控制器之间数据的传递 第一种方法: 复制代码 代码如下: self.parentViewController.music=self.music[indexPath.row]; 不能满足 第二种做法:把整个数组传递给它 第三种做法:设置一个数据源,设置播放控制器的数据源是这个控制器.self.parentViewController.dataSource=self;好处:没有耦合性,任何实现了协议的可以作为数据源. 第四种做法:把整个项目会使用到的音频资源交给一个工具类去

  • iOS获取本地音频文件(属性/信息)

    本文实例为大家分享了iOS获取本地音频文件的具体代码,供大家参考,具体内容如下 获取本地音频文件地址: NSString *songsDirectory=MUSIC_FILE_ALL;//沙盒地址 NSBundle *songBundle=[NSBundle bundleWithPath:songsDirectory]; NSString *bundlePath=[songBundle resourcePath]; NSArray *arrMp3=[NSBundle pathsForResour

  • iOS开发中音频视频播放的简单实现方法

    前言 我们在平时的iOS开发中,音视频的播放有很多种,目前系统的自带的都属于 AVFoundation 框架,更加接近于底层,所以灵活性很强,更加方便自定义 还有就是第三方音视频视频播放,特点是功能强大,实现简单,支持流媒体,下面来逐一介绍,给大家参考学习,下面来一起看看详细的介绍吧. 播放系统音效或者短音效 注意: 这里的资源长度最多30秒 资源必须在 Target --> Build Phases --> Copy Bundle Resources 引入资源文件,否则获取不到文件 if l

随机推荐