实现思路
利用系统框架AVFoundation实现录音和录音播放
AudioSession简介
iOS 通过sessions和AudioSession APIs处理音频行为
//获取session
[AVAudioSession sharedInstance]
设置Category 通过调用音频会话对象的setCategory:error:实例方法,来从iOS应用可用的不同类别中作出选择
/* set session category */
- (BOOL)setCategory:(NSString *)category error:(NSError **)outError;
/* set session category with options */
- (BOOL)setCategory:(NSString *)category withOptions: (AVAudioSessionCategoryOptions)options error:(NSError **)outError NS_AVAILABLE_IOS(6_0);
//Category 的类型
* AVAudioSessionCategorySoloAmbient
会停止其他程序的音频播放。当设备被设置为静音模式,app也同样被停止
* AVAudioSessionCategoryRecord
仅用来录音,无法播放音频
* AVAudioSessionCategoryPlayback
会停止其它音频播放,并且能在后台播放,锁屏and静音模式下均可
* AVAudioSessionCategoryPlayAndRecord
能播也能录,播放默认声音是从听筒出来
* AVAudioSessionCategoryAmbient
app的声音可与其它app共存,但锁屏和静音情况会被停止,除非当前app是唯一播放的app
录音核心的代码如下:
AVAudioSession *session =[AVAudioSession sharedInstance];
NSError *sessionError;
[session setCategory:AVAudioSessionCategoryAmbient error:&sessionError];
if (session) {
[session setActive:YES error:nil];
}else{
NSLog(@"%@",[sessionError description]);
}
self.session = session;
//1.获取沙盒地址
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
filePath = [path stringByAppendingString:@"/record.wav"];
NSLog(@"path : %@",filePath);
//2.获取文件路径
self.fileUrl = [NSURL fileURLWithPath:filePath];
//设置参数
NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
//采样率 8000/11025/22050/44100/96000(影响音频的质量)
[NSNumber numberWithFloat: 8000.0],AVSampleRateKey,
// 音频格式
[NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
//采样位数 8、16、24、32 默认为16
[NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
// 音频通道数 1 或 2
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
//录音质量
[NSNumber numberWithInt:AVAudioQualityMax],AVEncoderAudioQualityKey,
nil];
self.recorder = [[AVAudioRecorder alloc] initWithURL:self.fileUrl settings:recordSetting error:nil];
if (self.recorder) {
self.recorder.meteringEnabled = YES;
[self.recorder prepareToRecord];
[self.recorder record];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self stopRecord:nil];
});
}else{
NSLog(@"无法初始化recorder");
}
播放核心代码如下:
[self.recorder stop];
if ([self.player isPlaying]) {
return;
}
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.fileUrl error:nil];
[self.session setCategory:AVAudioSessionCategoryPlayback error:nil];
[self.player play];
一个参考链接 点击链接
网友评论