iOS中调用系统录音功能及其播放

瘦欲@ 提交于 2019-12-28 23:25:52

最近做的项目中,用到了录音的功能,简单记录一下。

我的想法是:通过重写button的点击事件,来达到录音的目的。

/*----------------------------------【录音】-----------------------------*/

首先,需要新建文件,并继承于UIButton,暂且命名为 TDRecoedButton;

在.h文件中:

#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>


typedef void (^successRecordToSend)(NSInteger time,NSURL *url);
typedef void (^faildRecordToSend)(NSString * reason);

@interface TDRecoedButton : UIButton<AVAudioRecorderDelegate>
{
    AVAudioRecorder *recorder;  //录音的对象
    NSTimer *timer;        //时间
    NSURL *urlPlay;        //保存路径
}

//录音并保存成功
@property (nonatomic,copy) successRecordToSend successBlock;
-(void)setBtnSuccessRecord:(successRecordToSend)sendBlock;

//录音失败及返回reason方法
@property (nonatomic,copy) faildRecordToSend faildBlock;
-(void)setBtnFaildRecord:(faildRecordToSend)sendBlock;

 

在.m文件中:

#import "TDRecoedButton.h"
#define reason @"录音时间太短!"

@implementation TDRecoedButton

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self audio];
        [self setBackgroundImage:[UIImage imageNamed:@"icon_voice_normal"] forState:UIControlStateNormal];
        [self setBackgroundImage:[UIImage imageNamed:@"icon_voice_pressed"] forState:UIControlStateHighlighted];
        [self addTarget:self action:@selector(btnDown:) forControlEvents:UIControlEventTouchDown];
        [self addTarget:self action:@selector(btnUp:) forControlEvents:UIControlEventTouchUpInside];
        [self addTarget:self action:@selector(btnDragUp:) forControlEvents:UIControlEventTouchDragExit];
    }
    return self;
}

- (IBAction)btnDown:(id)sender
{
    //创建录音文件,准备录音
    if ([recorder prepareToRecord]) {
        //开始
        [recorder record];
    }
    
    //设置定时检测
//    timer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(detectionVoice) userInfo:nil repeats:YES];
}
- (IBAction)btnUp:(id)sender
{
    NSInteger cTime = recorder.currentTime;
    if (cTime > 1) {//如果录制时间<1 不发送
        NSLog(@"发出去");
        if (_successBlock) {
            _successBlock(cTime,urlPlay);
        }
    }else {
        //删除记录的文件
        [recorder deleteRecording];
        //删除存储的
        if (_faildBlock) {
            _faildBlock(reason);
        }
    }
    [recorder stop];
    [timer invalidate];
}
- (IBAction)btnDragUp:(id)sender
{
    //删除录制文件
    [recorder deleteRecording];
    [recorder stop];
    [timer invalidate];
    
    NSLog(@"取消发送");
}

-(void)audio
{
    //录音设置
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];
    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    //设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量)
    [recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];
    //录音通道数  1 或 2
    [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
    //线性采样位数  8、16、24、32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    
    NSString *strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/byingRecord.aac", strUrl]];
    NSLog(@"*********url:%@",url);
    urlPlay = url;
    
    NSError *error;
    //初始化
    recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&error];
    //开启音量检测
    recorder.meteringEnabled = YES;
    recorder.delegate = self;
}

-(void)setBtnSuccessRecord:(successRecordToSend)sendBlock
{
    self.successBlock = sendBlock;
}
-(void)setBtnFaildRecord:(faildRecordToSend)sendBlock
{
    self.faildBlock = sendBlock;
}

 

这样,重写的button就成功了,在别的控制器中,导入头文件,生成对象,就可以录音了。

但是,这样写,在模拟器上运行是完全ok的,当我跑真机的时候,就一直报错,于是,我找了一些帖子,找到了解决办法。

解决办法:

在实例化record之前,加入以下这段代码:

AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *setCategoryError = nil;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryError];
    if(setCategoryError){
        NSLog(@"%@", [setCategoryError description]);
        if (_faildBlock) {
            _faildBlock([setCategoryError description]);
        }
    }

这样就可以在真机上运行了。

 

/*----------------------------------【播放】-----------------------------*/

播放相对就简单了,主要就是找到存储的路径:

首先,定义一个对象:

@property (nonatomic,strong) AVAudioPlayer * avPlay;        /*播放*/

@property (nonatomic,strong) NSURL * urlPlay;                /*播放路径*/

在播放按钮的点击事件中,加入此方法:

#pragma mark - 点击播放录音
-(void)pressRecordPlayBtn:(id)sender
{
    if (self.avPlay.playing) {
        [self.avPlay stop];
        return;
    }
    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:_urlPlay error:nil];//_urlPlay是保存录音的路径
    self.avPlay = player;
    [self.avPlay play];
}

这样,就可以实现录音和播放的功能了!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!