#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
// AVAudioRecorder 实现相关功能
@property (strong, nonatomic) AVAudioRecorder *recorder;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
/**
如果运行在真机上, 需要做一些额外配置 (麦克风的访问授权)
*/
// 向系统声明App会使用到哪些音频相关的功能
NSError *sessionError;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:&sessionError];
if (sessionError) {
NSLog(@"AudioSessionError: %@", sessionError);
}
// URL是录音文件保存的路径
// 只有沙盒可以保存文件, Document
NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
// 默认是.aac格式
NSString *filePath = [documentPath stringByAppendingPathComponent:@"recod.aac"];
// 两种方式都可以
NSURL *url = [NSURL URLWithString:filePath];
// 带 file://
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSLog(@"url: %@, fileURL: %@", url, fileURL);
NSError *error;
/**
NSString *const AVFormatIDKey; 录音文件的格式, .aac, .mp3, .wav
NSString *const AVSampleRateKey; 采样率
NSString *const AVNumberOfChannelsKey; 音频通道数
*/
// URL在实例化后是不可修改, 一对一关系
NSDictionary *dict = @{
// 录音文件的格式
AVFormatIDKey : @(kAudioFormatMPEG4AAC) //.aac
};
// Settings是需要配置的, 不能为nil
_recorder = [[AVAudioRecorder alloc] initWithURL:fileURL settings:dict error:&error];
// 准备录音, 创建文件(等待数据写入), 硬件准备
[_recorder prepareToRecord];
}
- (IBAction)beginRecordAction:(id)sender
{
// 开始录音, 向文件写入数据
// 如果没有处于准备状态, 会隐式的调用prepareToRecord
[_recorder record];
}
- (IBAction)pauseRecordAction:(id)sender
{
// 是否正在录音
if (_recorder.isRecording) {
// 暂停录音
[_recorder pause];
} else {
// 开始录音
[_recorder record];
}
}
- (IBAction)stopRecordAction:(id)sender
{
// 停止录音, 释放(关闭)文件, 释放硬件准备
[_recorder stop];
}
@end
实用知识:录音功能的实现
最新推荐文章于 2018-04-08 16:38:46 发布