需求
某處功能加上錄音功能获列,時(shí)間大概60秒,上傳到服務(wù)器擎宝,服務(wù)器要求文件大小控制在1M以內(nèi)水评。
實(shí)現(xiàn)思路
利用系統(tǒng)框架AVFoundation實(shí)現(xiàn)錄音和錄音播放
實(shí)現(xiàn)步驟
一. 添加AVFoundation
二. 在需要的文件導(dǎo)入AVFoundation
#import <AVFoundation/AVFoundation.h>
三.核心代碼
* 開始錄音
- (IBAction)startRecord:(id)sender {
NSLog(@"開始錄音");
countDown = 60;
[self addTimer];
AVAudioSession *session =[AVAudioSession sharedInstance];
NSError *sessionError;
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
if (session == nil) {
NSLog(@"Error creating session: %@",[sessionError description]);
}else{
[session setActive:YES error:nil];
}
self.session = session;
//1.獲取沙盒地址
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
filePath = [path stringByAppendingString:@"/RRecord.wav"];
//2.獲取文件路徑
self.recordFileUrl = [NSURL fileURLWithPath:filePath];
//設(shè)置參數(shù)
NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
//采樣率 8000/11025/22050/44100/96000(影響音頻的質(zhì)量)
[NSNumber numberWithFloat: 8000.0],AVSampleRateKey,
// 音頻格式
[NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
//采樣位數(shù) 8、16、24兆蕉、32 默認(rèn)為16
[NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
// 音頻通道數(shù) 1 或 2
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
//錄音質(zhì)量
[NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,
nil];
_recorder = [[AVAudioRecorder alloc] initWithURL:self.recordFileUrl settings:recordSetting error:nil];
if (_recorder) {
_recorder.meteringEnabled = YES;
[_recorder prepareToRecord];
[_recorder record];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self stopRecord:nil];
});
}else{
NSLog(@"音頻格式和文件存儲(chǔ)格式不匹配,無法初始化Recorder");
}
}
*停止錄音
- (IBAction)stopRecord:(id)sender {
[self removeTimer];
NSLog(@"停止錄音");
if ([self.recorder isRecording]) {
[self.recorder stop];
}
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
_noticeLabel.text = [NSString stringWithFormat:@"錄了 %ld 秒,文件大小為 %.2fKb",COUNTDOWN - (long)countDown,[[manager attributesOfItemAtPath:filePath error:nil] fileSize]/1024.0];
}else{
_noticeLabel.text = @"最多錄60秒";
}
}
*播放錄音
- (IBAction)PlayRecord:(id)sender {
NSLog(@"播放錄音");
[self.recorder stop];
if ([self.player isPlaying])return;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.recordFileUrl error:nil];
NSLog(@"%li",self.player.data.length/1024);
[self.session setCategory:AVAudioSessionCategoryPlayback error:nil];
[self.player play];
}
demo地址:https://github.com/Rachel829/RLAudioRecord
效果圖: