博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS设备发送语音信息相关功能代码
阅读量:7063 次
发布时间:2019-06-28

本文共 7926 字,大约阅读时间需要 26 分钟。

hot3.png

首先得对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
 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];    }];}

转载于:https://my.oschina.net/pingAds/blog/408537

你可能感兴趣的文章
[leetcode]Search a 2D Matrix @ Python
查看>>
java.io.BufferedOutputStream 源码分析
查看>>
Load resources from classpath in Java--reference
查看>>
关于LightMapping和NavMesh烘焙的动态载入
查看>>
(转)Android中使用ormlite实现持久化(一)--HelloOrmLite
查看>>
C语言近程型(near)和远程型(far)的区别是什么?
查看>>
jQuery选择器总结
查看>>
《Continuous Delivery》 Notes 1: The problem of delivering software
查看>>
java android 将小数度数转换为度分秒格式
查看>>
一张图知道HTML5布局(图)
查看>>
LINQ To SQL在N层应用程序中的CUD操作、批量删除、批量更新
查看>>
谈谈javascript语法里一些难点问题(一)
查看>>
【BZOJ】1082: [SCOI2005]栅栏(二分+dfs)
查看>>
通过递归组合多维数组!
查看>>
ocp 1Z0-051 23-70题解析
查看>>
关于MFLAGS与MAKEFLAGS
查看>>
NotePad++ for PHP
查看>>
ssh事务回滚,纪念这几个月困扰已久的心酸
查看>>
jQuery中的编程范式
查看>>
比较快速排序,冒泡排序,双向冒泡排序的执行效率
查看>>