AVFoundation-如何实现简单的语音备忘录

317 阅读2分钟

用到的类

AVAudioRecorder:音频录制

AVAudioPlayer:音频播放

1.准备阶段

在info.plist文件添加Privacy - Microphone Usage Description描述字段,同意用户访问麦克风
在applegate的didFinishLaunchingWithOptions方法中添加如下设置
- (void)setupAudioSession
{
    AVAudioSession *session = [AVAudioSession sharedInstance];

    /*

     AVAudioSessionCategoryAmbient 允许混音 不允许音频输入 允许音频输出

     AVAudioSessionCategorySoloAmbient 不允许混音 不允许音频输入 允许音频输出

     AVAudioSessionCategoryPlayback 混音可选 不允许音频输入 允许音频输出

     AVAudioSessionCategoryRecord 不允许混音 允许音频输入 不允许音频输出

     AVAudioSessionCategoryPlayAndRecord 混音可选 允许音频输入 允许音频输出

     AVAudioSessionCategoryAudioProcessing 离线会话处理

     AVAudioSessionCategoryMultiRoute 使用外部硬件的高级A/V应用程序 允许混音 允许音频输入 允许音频输出

     */

    NSError *error;

    if (![session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error]) {

        NSLog(@"Category Error: %@", [error localizedDescription]);

    }

    if (![session setActive:YES error:&error]) {

        NSLog(@"Activation Error: %@", [error localizedDescription]);

    }
}

2.初始化AVAudioRecorder

初始化方法:initWithURL: settings: error:
第一个参数:NSURL类型,本地存储的URL
第二个参数:NSDictionary类型,设置音频的参数
    AVFormatIDKey:音频的类型
    AVSampleRateKey:样本率
    AVNumberOfChannelsKey:声道数
    AVEncoderBitDepthHintKey:位深
    AVEncoderAudioQualityKey:音频质量
第三个参数:NSError类型,错误信息
示例:
NSString *filePath = [NSTemporaryDirectory() stringByAppendingFormat:@"memo.caf"];

NSURL *fileURL = [NSURL fileURLWithPath:filePath];

NSDictionary *settings = @{

            AVFormatIDKey : @(kAudioFormatAppleIMA4),

            AVSampleRateKey : @44100.f,

            AVNumberOfChannelsKey : @1,

            AVEncoderBitDepthHintKey : @16,

            AVEncoderAudioQualityKey : @(AVAudioQualityMedium)

        };
        
NSError *error;

self.recorder = [[AVAudioRecorder alloc] initWithURL:fileURL settings:settings error:&error];

if (self.recorder) {

    _recorder.delegate = self;

    _recorder.meteringEnabled = YES;

    [_recorder prepareToRecord];

}

3.开始录制

返回BOOL类型,是否成功开始录音
[self.recorder record];

4.停止录制

[self.recorder pause];

5.结束录制

[self.recorder stop];
结束完成后会走AVAudioRecorder的代理方法,在这里处理结束录制的回调处理
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{ 
}

6.保存本地,这里可以自行抉择使用什么本地化存储

7.播放本地录音

//初始化
NSError *error;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:memo.url error:&error];
//播放
if (self.player) {
    [self.player play];
}

Mark:如果想获取录音时的音量大小,可以使用AVRecorder的两个方法averagePowerForChannel和peakPowerForChannel