实用知识:录音功能的实现

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值