OC-錄制本地音頻

#import <Foundation/Foundation.h>

/// 錄音采樣率(Hz)
typedef NS_ENUM(NSInteger, AudioSampleRate) {
    AudioSampleRateLow = 8000,
    AudioSampleRateMedium = 44100,//CD
    AudioSampleRateHigh = 96000
};

/// 線性采樣位數(shù)-采樣精度(bit)
typedef NS_ENUM(NSInteger, AudioLinearPCMBit) {
    AudioLinearPCMBitLow = 8,
    AudioLinearPCMBitMedium = 16,//CD
    AudioLinearPCMBitHigh = 24,
    AudioLinearPCMBitMax = 32
};

@interface LilyRecorder : NSObject
@property (nonatomic, strong) NSString * pcmAudioPath;
@property (nonatomic, strong) NSString * mp3AudioPath;

//實列化
+(LilyRecorder*)sharedAudioRecorder;
//初始化錄音器
-(void)createAudioRecorder;

// 開始錄音
- (void)startRecording;
// 停止錄音
- (void)stopRecording;
@end
#import "LilyRecorder.h"
#import <AVFoundation/AVFoundation.h>

@interface LilyRecorder ()<AVAudioRecorderDelegate>
@property(nonatomic,strong) AVAudioRecorder * recorder;
@property(nonatomic,strong) AVAudioSession * session;
@property(nonatomic,strong) NSMutableDictionary * recordSettingDictionary;

@property (nonatomic, assign) BOOL isStopRecording;
@property (nonatomic, strong) dispatch_semaphore_t semaphore;
@end

static LilyRecorder * manager = nil;
@implementation LilyRecorder
+(id)sharedAudioRecorder
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[LilyRecorder alloc] init];
        manager.semaphore = dispatch_semaphore_create(1);
    });
    return manager;
}

#pragma mark - 初始化錄音器
-(void)createAudioRecorder
{
    NSURL * url = [NSURL fileURLWithPath:self.pcmAudioPath];
    _recorder = [[AVAudioRecorder alloc] initWithURL:url settings:_recordSettingDictionary error:nil];
    _recorder.delegate = self;
    _recorder.meteringEnabled = YES;
    [_recorder prepareToRecord];
}

#pragma mark - 開始錄音
- (void)startRecording
{
    /**
     *  !!!!在錄音之前要重新設置音頻會話,雖然初始化時設置AVAudioSessionCategoryPlayAndRecord,但是因為
     *  使用了AVPlayer播放音視頻,所以會將音頻會話隱式轉為AVAudioSessionCategoryPlayback,故錄音時會出
     *  現(xiàn)錄音失敗的情況,因此在錄音之前要重新設置音頻會話為AVAudioSessionCategoryPlayAndRecord。
     */
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [self.recorder record];
}

#pragma mark - 停止錄音
- (void)stopRecording
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ //避免結束錄音后,尾部數(shù)據(jù)丟失
        [self.recorder stop];
        self.isStopRecording = YES;
    });
}

#pragma mark - AVAudioRecord Delegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    DLog(@"finish recording");
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error {
    DLog(@"recorder error");
}


#pragma mark - 懶加載
- (void)setUpRecordingSettings {
    _recordSettingDictionary = [NSMutableDictionary dictionary];
    //錄音格式 無法使用
    [_recordSettingDictionary setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey: AVFormatIDKey];
    //采樣率
    [_recordSettingDictionary setValue :[NSNumber numberWithFloat:AudioSampleRateMedium] forKey: AVSampleRateKey];//44100.0
    //通道數(shù)
    [_recordSettingDictionary setValue :[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];
    //線性采樣位數(shù)
    [_recordSettingDictionary setValue :[NSNumber numberWithInt:AudioLinearPCMBitMedium] forKey: AVLinearPCMBitDepthKey];
    //音頻質量,采樣質量
    [_recordSettingDictionary setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
}

- (void)setUpAudioSession {
    _session = [AVAudioSession sharedInstance];
    [_session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [_session setActive:YES error:nil];
    [_session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];//揚聲器播放
}
@end
//初始化錄音器
[LilyRecorder sharedAudioRecorder].pcmAudioPath = @"錄音文件保存路徑";
[[LilyRecorder sharedAudioRecorder] createAudioRecorder];

//開始錄音
[[LilyRecorder sharedAudioRecorder] startRecording];

//結束錄音
[[LilyRecorder sharedAudioRecorder] stopRecording];
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容