[iOS]录音库封装

本文详细介绍了如何在iOS平台上进行录音操作,包括使用内置的录音库进行音频录制,并且讲解了如何将录音功能进行封装,以便在多个地方复用。通过实例代码和步骤解析,帮助开发者理解iOS录音的核心技术和实践技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import "Constant.h"



@interface STAudioManager : NSObject<AVAudioRecorderDelegate, AVAudioPlayerDelegate>

@property (nonatomic, strong) AVAudioRecorder *recorder;
@property (nonatomic, strong) AVAudioSession *session;
@property (nonatomic, copy) NSURL *recordFileUrl;
@property (nonatomic, copy) NSString *filePath;

SingletonH(STAudioManager)

// set save path
- (NSString *)setupPath;

// start recordd
- (void)startRecord;

// pause record
- (void)pauseRecord;

// continue record
- (void)continueRecordd;

// stop record
- (void)stopRecord;

// get audio time
- (float)getAudioAllTime;


@end

.m 

#define AudioType @"aac"

#import "STAudioManager.h"

@implementation STAudioManager

HMSingletonM(STAudioManager)

- (NSString *)setupPath
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    NSString *timeStampStr = [NSString stringWithFormat:@"%.f",timeStamp];
    NSString *filePath = [path stringByAppendingFormat:@"/%@.%@",timeStampStr, AudioType];
    // TODO: 采用fileUrlWithPath 否则取不到语音时长
    self.recordFileUrl = [NSURL fileURLWithPath:filePath];
    self.filePath = filePath;
    NSLog(@"录音文件保存地址------->%@",self.filePath);
    return filePath;
}


- (AVAudioRecorder *)recorder
{
    if (!_recorder) {
        
        AVAudioSession *sessionTemp =[AVAudioSession sharedInstance];
        NSError *sessionError;
        [sessionTemp setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if (sessionTemp == nil) {
            NSLog(@"Error creating session: %@",[sessionError description]);
            return nil;
        }else{
            [sessionTemp setActive:YES error:nil];
        }
        self.session = sessionTemp;
        //创建录音格式设置
        NSDictionary *setting = [self getAudioSetting];
        //创建录音机
        NSError *error = nil;
        _recorder = [[AVAudioRecorder alloc]initWithURL:self.recordFileUrl settings:setting error:&error];
        _recorder.delegate = self;
        //        _recorder.meteringEnabled = YES;//如果要监控声波则必须设置为YES
        if (error) {
            NSLog(@"创建录音机对象时发生错误,错误信息:%@",error.localizedDescription);
            return nil;
        }
        
        NSLog(@"recorder 创建完成:%@",self.recordFileUrl);
        
//        [_recorder prepareToRecord];
        
        NSLog(@"recorder prepare");
    }
    return _recorder;
    
}

- (NSDictionary *)getAudioSetting
{
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    //采样率  8000/11025/22050/44100/96000(影响音频的质量)
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    //设置通道,这里采用单声道
    [dicM setObject:@(1) forKey:AVNumberOfChannelsKey];
    // 编码格式
    [dicM setObject:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];
    // 录音质量
    [dicM setObject:@(AVAudioQualityHigh) forKey:AVEncoderAudioQualityKey];
    // 每个采样点位
    [dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];
    // 浮点数采样
    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    
    
    return dicM;
}

- (void)startRecord
{
    if ([self.recorder isRecording]) {
        [self.recorder stop];
        [self.recorder record];
    } else {
        [self.recorder record];
    }
}

- (void)pauseRecord
{
    if ([self.recorder isRecording]) {
        [self.recorder pause];
    }
}

- (void)continueRecordd
{
    [self startRecord];
}

- (void)stopRecord
{
    if ([self.recorder isRecording]) {
        [self.recorder stop];
    }
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:self.filePath]) {
        NSLog(@"文件大小为:%.2llukb", [[manager attributesOfItemAtPath:self.filePath error:nil] fileSize]/1024);
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"文件时长为:%.f", [self getAudioAllTime]);
    });
}

// get audio time
- (float)getAudioAllTime
{
    AVURLAsset *audioAsset = [AVURLAsset URLAssetWithURL:self.recordFileUrl options:nil];
    CMTime duration = audioAsset.duration;
    NSInteger resultTime = 0;
    resultTime = CMTimeGetSeconds(duration);
    return resultTime;
}

@end

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值