首先得对AVAudioSession音频会话对象进行设置:
//获取AVAudioSession对象
_audioSession = [AVAudioSession sharedInstance];
//设置类别,该类别允许应用同时进行声音的播放和录制
[_audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
再对AVAudioRecorder进行基本设置(如通道数,采样率,录音格式等):
//对AVAudioRecorder进行一些设置
NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0],AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
[NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
[NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
[NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey, nil];
//录音存放的地址文件
_recordingUrl = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"myRecord.wav"]];
//初始化AVAudioRecorder
_audioRecorder = [[AVAudioRecorder alloc] initWithURL:_recordingUrl settings:recordSetting error:nil];
//对录音开启音量检测
_audioRecorder.meteringEnabled = YES;
//设置代理
_audioRecorder.delegate = self;
设置一个录音按钮,添加两个事件,分别在长按按钮和松开长按按钮时执行,长按时录音开始进行,松开后录音结束:
//长按录音
- (void)StartRecordingVoice
{
NSLog(@"开始 录音");
//判断是否是第一次录制
if (recordNumber > 1) {
[self recordAgain];
}
_audioSession = [AVAudioSession sharedInstance];
if (!_audioRecorder.recording) {
recordNumber++;
hasVoice = YES;
_timesLabel.hidden = NO;
_textLabel.text = @"放开 停止";
[_audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[_audioSession setActive:YES error:nil];
[_audioRecorder prepareToRecord];
[_audioRecorder peakPowerForChannel:0.0];
[_audioRecorder record];
recordTime = 0;
//刷新时间
[self recordTimeStart];
}
}
- (void)recordTimeStart
{
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(recordTime) userInfo:nil repeats:YES];
}
- (void)recordTime
{
recordTime += 1;
if (recordTime == 30) {
recordTime = 0;
[_audioRecorder stop];
[[AVAudioSession sharedInstance] setActive:NO error:nil];
[timer invalidate];
_timesLabel.text = @"00:00";
return;
}
[self updateRecordTime];
}
- (void)updateRecordTime
{
minute = recordTime/60.0;
second = recordTime-minute*60;
_timesLabel.text = [NSString stringWithFormat:@"%02d:%02d", minute, second];
}
//停止录音
- (void)StopRecordingVoice
{
NSLog(@"停止 录音");
_audioSession = [AVAudioSession sharedInstance];
if (_audioRecorder.isRecording) {
int seconds = minute*60+second;
_voiceTimes.text = [NSString stringWithFormat:@"%d\" ",seconds];
_voiceImageView.hidden = NO;
_voiceTimes.hidden = NO;
_textLabel.text = @"长按 录音";
[_audioRecorder stop];
[_audioSession setActive:NO error:nil];
[timer invalidate];
[self updateRecordTime];
}
}
设置一个播放按钮,第一次点击时开始播放,再点击时停止播放:
//播放录音
- (void)PlayVoice
{
_audioSession = [AVAudioSession sharedInstance];
if (isPlay) {
NSLog(@"暂停");
[_playButton setImage:[UIImage imageNamed:@"voice_play.png"] forState:UIControlStateNormal];
isPlay = NO;
[_voiceImageView stopAnimating];
[_audioPlayer pause];
[_audioSession setActive:NO error:nil];
} else {
NSLog(@"播放中");
_voiceImageView.hidden = NO;
_voiceTimes.hidden = NO;
[_voiceImageView startAnimating];
[_playButton setImage:[UIImage imageNamed:@"voice_pause.png"] forState:UIControlStateNormal];
isPlay = YES;
[_audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[_audioSession setActive:YES error:nil];
NSError *error = nil;
if (_recordingUrl != nil) {
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:_recordingUrl error:&error];
}
if (error) {
NSLog(@"error:%@", [error description]);
}
[_audioPlayer prepareToPlay];
_audioPlayer.volume = 1;
[_audioPlayer play];
//播放时间
playDuration = (int)_audioPlayer.duration;
playTimes = 0;
[self audioPlayTimesStart];
}
}
//播放时间
- (void)audioPlayTimesStart
{
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playTimeTick) userInfo:nil repeats:YES];
}
- (void)playTimeTick
{
//当播放时长等于音频时长时,停止跳动。
if (playDuration == playTimes) {
NSLog(@"已播完");
isPlay = NO;
[_playButton setImage:[UIImage imageNamed:@"voice_play.png"] forState:UIControlStateNormal];
[_voiceImageView stopAnimating];
playTimes = 0;
[_audioPlayer stop];
[[AVAudioSession sharedInstance] setActive:NO error:nil];
[timer invalidate];
return;
}
if (!_audioPlayer.isPlaying) {
return;
}
playTimes += 1;
NSLog(@"playDuration:%d playTimes:%d", playDuration, playTimes);
}
设置一个发送语音信息按钮:
(void)postVoice{
MBProgressHUD *HUD = [Utils createHUD];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFOnoResponseSerializer XMLResponseSerializer];
[manager POST:_postUrl
parameters:@{
@"userId": @([Config getOwnID]),
@"message": [Utils convertRichTextToRawText:_edittingArea]
}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (_recordingUrl.absoluteString.length) {
NSError *error = nil;
NSString *voicePath = [NSString stringWithFormat:@"%@myRecord.wav", NSTemporaryDirectory()];
[formData appendPartWithFileURL:[NSURL fileURLWithPath:voicePath isDirectory:NO]
name:@"amr"
fileName:@"myRecord.wav"
mimeType:@"audio/mpeg"
error:&error];
}
}
success:^(AFHTTPRequestOperation *operation, ONOXMLDocument *responseDocument) {
ONOXMLElement *result = [responseDocument.rootElement firstChildWithTag:@"result"];
int errorCode = [[[result firstChildWithTag:@"errorCode"] numberValue] intValue];
NSString *errorMessage = [[result firstChildWithTag:@"errorMessage"] stringValue];
HUD.mode = MBProgressHUDModeCustomView;
[HUD show:YES];
if (errorCode == 1) {
_edittingArea.text = @"";
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"HUD-done"]];
HUD.labelText = @"语音发表成功";
} else {
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"HUD-error"]];
HUD.labelText = [NSString stringWithFormat:@"错误:%@", errorMessage];
}
[HUD hide:YES afterDelay:1];
[self dismissViewControllerAnimated:YES completion:nil];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
HUD.mode = MBProgressHUDModeCustomView;
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"HUD-error"]];
HUD.labelText = @"网络异常,语音发送失败";
[HUD hide:YES afterDelay:1];
}];
}