AVAudioRecorder

0 使用前准备

这是一个录制音频的类.1.需要设置AVAudioSession.2.需要在info.plist中添加相应的字段

0.1 设置AVAudioSession接收音频输入

NSError *error;
AVAudioSession *session = [AVAudioSession sharedInstance];
if ([session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error]) {
	// 处理错误
}

0.2 在info.plist中添加对应字段

Privacy - Microphone Usage Description(NSMicrophoneUsageDescription).后面的内容是为什么要使用麦克风的说明.一般的套路就是.需要使用您的麦克风来干XXX,如果不同意,则xxx功能不能使用.这个得注意,不填不能过审.

1 类介绍

/// 创建方法
- (nullable instancetype)initWithURL:(NSURL *)url settings:(NSDictionary<NSString *, id> *)settings error:(NSError **)outError;
- (nullable instancetype)initWithURL:(NSURL *)url format:(AVAudioFormat *)format error:(NSError **)outError API_AVAILABLE(macos(10.12), ios(10.0), watchos(4.0)) API_UNAVAILABLE(tvos);

/// 创建音频文件并准备进行录制(调用record时,会自动调用.)该方法会在initWithURL: setting: error方法中的url的位置创建音频文件,如果该位置已经有此文件,该方法将会覆盖该文件.
- (BOOL)prepareToRecord;
/// 开始/恢复 录制.(PS:内部会自动调用prepareToRecord)
- (BOOL)record;
/// 将在time秒后继续录制.time得(myAudioRecorder.deviceCurrentTime + time)
- (BOOL)recordAtTime:(NSTimeInterval)time API_AVAILABLE(macos(10.9), ios(6.0), watchos(4.0)) API_UNAVAILABLE(tvos);
/// 录制持续时间(duration)后就会自动停止
- (BOOL)recordForDuration:(NSTimeInterval) duration; 
/// time秒后开始录制.然后duration秒后停止
- (BOOL)recordAtTime:(NSTimeInterval)time forDuration:(NSTimeInterval) duration API_AVAILABLE(macos(10.9), ios(6.0), watchos(4.0)) API_UNAVAILABLE(tvos); /* record a file of a specified duration starting at specified time. time is an absolute time based on and greater than deviceCurrentTime. */
/// 暂停录制
- (void)pause;
/// 停止录制.关闭文件输出
- (void)stop;
/// 删除录制(必须得先调用stop方法)
- (BOOL)deleteRecording;

/* 属性 */

/// 录音机是否正在录制
@property(readonly, getter=isRecording) BOOL recording;

/// 录制文件的url
@property(readonly) NSURL *url;

/// 录制设置
@property(readonly) NSDictionary<NSString *, id> *settings;

/// format
@property(readonly) AVAudioFormat *format API_AVAILABLE(macos(10.12), ios(10.0), watchos(4.0)) API_UNAVAILABLE(tvos);

/// 代理
@property(weak, nullable) id<AVAudioRecorderDelegate> delegate;

/// 当前的录制时间.仅在录制时有效
@property(readonly) NSTimeInterval currentTime;
/// 获取设备当前时间,始终有效
@property(readonly) NSTimeInterval deviceCurrentTime API_AVAILABLE(macos(10.9), ios(6.0), watchos(4.0)) API_UNAVAILABLE(tvos);

/* 计量 */
/// 是否能计量
@property(getter=isMeteringEnabled) BOOL meteringEnabled; /* turns level metering on or off. default is off. */

/// 更新计量
- (void)updateMeters;

/// 返回通道的峰值功率(分贝值)
- (float)peakPowerForChannel:(NSUInteger)channelNumber; /* returns peak power in decibels for a given channel */
/// 返回通道的平均功率(分贝值)
- (float)averagePowerForChannel:(NSUInteger)channelNumber; /* returns average power in decibels for a given channel */

/// 可以设置记录通道
@property(nonatomic, copy, nullable) NSArray<AVAudioSessionChannelDescription *> *channelAssignments API_AVAILABLE(ios(7.0), watchos(4.0)) API_UNAVAILABLE(macos) API_UNAVAILABLE(tvos); /* Array of AVAudioSessionChannelDescription objects */

@end

AVAudioRecorderDelegate

/// 录制完成时调用,如果因为中断停止,就不会调用这个方法
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag;

/// 录音机发生错误回调
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error;

/// MAKR: iOS有关

/// 开始打断
- (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder NS_DEPRECATED_IOS(2_2, 8_0);

/// 打断结束后调用
- (void)audioRecorderEndInterruption:(AVAudioRecorder *)recorder NS_DEPRECATED_IOS(2_2, 6_0);

/// 打断结束后调用.如果调用该方法就不调用上面的方法.
- (void)audioRecorderEndInterruption:(AVAudioRecorder *)recorder withOptions:(NSUInteger)flags NS_DEPRECATED_IOS(6_0, 8_0);

/// 打断结束后调用.如果调用该方法就不会调用上面的方法
- (void)audioRecorderEndInterruption:(AVAudioRecorder *)recorder withFlags:(NSUInteger)flags NS_DEPRECATED_IOS(4_0, 6_0);

AVAudioRecorder相关参数

formatsKey

AVFormatIDKey (音频格式)
CF_ENUM(AudioFormatID)
{
    kAudioFormatLinearPCM               = 'lpcm',
    kAudioFormatAC3                     = 'ac-3',
    kAudioFormat60958AC3                = 'cac3',
    kAudioFormatAppleIMA4               = 'ima4',
    kAudioFormatMPEG4AAC                = 'aac ',
    kAudioFormatMPEG4CELP               = 'celp',
    kAudioFormatMPEG4HVXC               = 'hvxc',
    kAudioFormatMPEG4TwinVQ             = 'twvq',
    kAudioFormatMACE3                   = 'MAC3',
    kAudioFormatMACE6                   = 'MAC6',
    kAudioFormatULaw                    = 'ulaw',
    kAudioFormatALaw                    = 'alaw',
    kAudioFormatQDesign                 = 'QDMC',
    kAudioFormatQDesign2                = 'QDM2',
    kAudioFormatQUALCOMM                = 'Qclp',
    kAudioFormatMPEGLayer1              = '.mp1',
    kAudioFormatMPEGLayer2              = '.mp2',
    kAudioFormatMPEGLayer3              = '.mp3',
    kAudioFormatTimeCode                = 'time',
    kAudioFormatMIDIStream              = 'midi',
    kAudioFormatParameterValueStream    = 'apvs',
    kAudioFormatAppleLossless           = 'alac',
    kAudioFormatMPEG4AAC_HE             = 'aach',
    kAudioFormatMPEG4AAC_LD             = 'aacl',
    kAudioFormatMPEG4AAC_ELD            = 'aace',
    kAudioFormatMPEG4AAC_ELD_SBR        = 'aacf',
    kAudioFormatMPEG4AAC_ELD_V2         = 'aacg',
    kAudioFormatMPEG4AAC_HE_V2          = 'aacp',
    kAudioFormatMPEG4AAC_Spatial        = 'aacs',
    kAudioFormatMPEGD_USAC              = 'usac',
    kAudioFormatAMR                     = 'samr',
    kAudioFormatAMR_WB                  = 'sawb',
    kAudioFormatAudible                 = 'AUDB',
    kAudioFormatiLBC                    = 'ilbc',
    kAudioFormatDVIIntelIMA             = 0x6D730011,
    kAudioFormatMicrosoftGSM            = 0x6D730031,
    kAudioFormatAES3                    = 'aes3',
    kAudioFormatEnhancedAC3             = 'ec-3',
    kAudioFormatFLAC                    = 'flac',
    kAudioFormatOpus                    = 'opus'
};

一般都是用AAC

AVSampleRateKey (取样率)

@44100

@8000 (电话采样率)

AVNumberOfChannelsKey (声道数)

@1 (单声道)

AVLinearPCMBitDepthKey (比特率)

8 16 24 32

AVLinearPCMIsBigEndianKey (大小端存储)

YES是大端存储,NO小端存储

AVLinearPCMIsFloatKey (采样信号是整数还是浮点数)

YES浮点数 NO整数

AVLinearPCMIsNonInterleaved

YES非交错 NO交错

音频类型key

AVAudioFileTypeKey (音频文件类型)
AVEncoderAudioQualityKey (音频编码质量)
typedef NS_ENUM(NSInteger, AVAudioQuality) {
	AVAudioQualityMin    = 0,
	AVAudioQualityLow    = 0x20,
	AVAudioQualityMedium = 0x40,
	AVAudioQualityHigh   = 0x60,
	AVAudioQualityMax    = 0x7F
};

AVEncoderAudioQualityForVBRKey (动态比特率)

值为AVAudioQuality类型

AVEncoderBitRateKey (编码比特率)
AVEncoderBitRatePerChannelKey (每个声道的比特率)

属性值

AVEncoderBitRateStrategyKey (编码比特率策略)
/* values for AVEncoderBitRateStrategyKey */
extern NSString *const AVAudioBitRateStrategy_Constant              API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
extern NSString *const AVAudioBitRateStrategy_LongTermAverage       API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
extern NSString *const AVAudioBitRateStrategy_VariableConstrained   API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
extern NSString *const AVAudioBitRateStrategy_Variable              API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
AVEncoderBitDepthHintKey

取值范围8 - 32

AVSampleRateConverterAlgorithmKey
extern NSString *const AVSampleRateConverterAlgorithm_Normal        API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
extern NSString *const AVSampleRateConverterAlgorithm_Mastering     API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
extern NSString *const AVSampleRateConverterAlgorithm_MinimumPhase  API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0));
AVSampleRateConverterAudioQualityKey
AVChannelLayoutKey

返回NSData类型.

用例

AVAudioSession *session = [AVAudioSession sharedInstance];
if ([session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]) {

}
NSURL *url = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"/录音.MP3"]];    
NSError *error;
self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:@{AVFormatIDKey :@(kAudioFormatMPEG4AAC),
      AVSampleRateKey :@(8000),
      AVNumberOfChannelsKey :@(1),
      AVLinearPCMBitDepthKey :@(8),
      AVLinearPCMIsFloatKey :@(YES)
    } error:&error];
self.audioRecorder.delegate = self;
[self.audioRecorder prepareToRecord];
[self.audioRecorder record];

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值