AVAudioPlayer
self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:self.fileUrl error:nil];
// 3.音频信息
NSString *msg = [NSString stringWithFormat:@"音频文件声道数:%ld\n 音频文件持续时间:%g",self.player.numberOfChannels,self.player.duration];
NSLog(@"%@",msg);
if (self.player) {
[self.player prepareToPlay];
[self.player play];
}
AVAudioRecorder
//(1)url
NSString *urlStr = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/recoder.aac"];
//删除之前的录音
[[NSFileManager defaultManager]removeItemAtPath:urlStr error:nil];
self.fileUrl = [NSURL fileURLWithPath:urlStr];
//(2)设置录音的音频参数
/*
1 ID号:acc
2 采样率(HZ):每秒从连续的信号中提取并组成离散信号的采样个数
3 通道的个数:(1 单声道 2 立体声)
4 采样位数(8 16 24 32) 衡量声音波动变化的参数
5 大端或者小端 (内存的组织方式)
6 采集信号是整数还是浮点数
7 音频编码质量
*/
NSDictionary *info = @{
AVFormatIDKey:[NSNumber numberWithInt:kAudioFormatMPEG4AAC],//音频格式
AVSampleRateKey:@8000,//采样率
AVNumberOfChannelsKey:@1,//声道数
AVLinearPCMBitDepthKey:@8,//采样位数
AVLinearPCMIsBigEndianKey:@NO,
AVLinearPCMIsFloatKey:@NO,
AVEncoderAudioQualityKey:[NSNumber numberWithInt:AVAudioQualityHigh],
};
/*
url:录音文件保存的路径
settings: 录音的设置
error:错误
*/
NSError * error;
self.recorder = [[AVAudioRecorder alloc]initWithURL:self.fileUrl settings:info error:&error];
self.recorder.delegate = self;
if(error) {
NSLog(@"错误%@", error); // 在这里我们简单打印错误, 在实际项目中我们要做容错判断
}
BOOL isno = [self.recorder prepareToRecord];
if (!isno) {
NSLog(@"失败");
}
[self.recorder record];
AVAudioSession
//开启扩音
self.section = [AVAudioSession sharedInstance];
NSError *sessionError;
[self.section setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (
kAudioSessionProperty_OverrideAudioRoute,
sizeof (audioRouteOverride),
&audioRouteOverride
);
if(self.section == nil)
NSLog(@"Error creating session: %@", [sessionError description]);
else
[self.section setActive:YES error:nil];