IOS之录音功能

第一步导入头文件

首先导入头文件#import 和#import "lame.h"


IOS之录音功能_第1张图片
导入录音的头文件

#######第二步 写访问权限 直接在info.plist里面都撸进去


    NSPhotoLibraryUsageDescription
    App需要您的同意,才能访问相册
    
    NSCameraUsageDescription
    App需要您的同意,才能访问相机
    
    NSMicrophoneUsageDescription
    App需要您的同意,才能访问麦克风
    
    NSLocationUsageDescription
    App需要您的同意,才能访问位置
    
    NSLocationWhenInUseUsageDescription
    App需要您的同意,才能在使用期间访问位置
    
    NSLocationAlwaysUsageDescription
    App需要您的同意,才能始终访问位置
    
    NSCalendarsUsageDescription
    App需要您的同意,才能访问日历
    
    NSRemindersUsageDescription
    App需要您的同意,才能访问提醒事项
    
    NSMotionUsageDescription App需要您的同意,才能访问运动与健身
    
    NSHealthUpdateUsageDescription
    App需要您的同意,才能访问健康更新 
    
    NSHealthShareUsageDescription
    App需要您的同意,才能访问健康分享
    
    NSBluetoothPeripheralUsageDescription
    App需要您的同意,才能访问蓝牙 
     
    NSAppleMusicUsageDescription 
    App需要您的同意,才能访问媒体资料库
第三步 初始化播放器 录音器 文件地址 定时器 这些控件
@property (nonatomic, strong) AVAudioSession *session;
@property (nonatomic, strong) AVAudioRecorder *recorder;//录音器
@property (nonatomic, strong) AVAudioPlayer *player; //播放器
@property (nonatomic, strong) NSURL *recordFileUrl; //文件地址
第四步 分别实现 录音 停止播放录音 和播放录音
//
//  ViewController.m
//  AudioRecord
//
//  Created by 辛忠志 on 17/4/13.
//  Copyright © 2017年 辛忠志. All rights reserved.
//
#import "ViewController.h"
#import 
#import "lame.h"
# define COUNTDOWN 60
@interface ViewController (){
    NSTimer *_timer; //定时器
    NSInteger countDown;  //倒计时
    NSString *filePath;
}
@property (weak, nonatomic) IBOutlet UILabel *noticeLabel;
@property (nonatomic, strong) AVAudioSession *session;
@property (nonatomic, strong) AVAudioRecorder *recorder;//录音器
@property (nonatomic, strong) AVAudioPlayer *player; //播放器
@property (nonatomic, strong) NSURL *recordFileUrl; //文件地址
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
}
- (IBAction)startRecord:(id)sender {
    NSLog(@"开始录音");
    countDown = 60;
    [self addTimer];
    //创建一个单例  在获得一个AVAudioSession类的实例后,你就能通过调用音频会话对象的setCategory:error:实例方法,来从IOS应用可用的不同类别中作出选择。下面列出了可供使用的音频会话类别:
    AVAudioSession *session =[AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    if (session == nil) {
        NSLog(@"Error creating session: %@",[sessionError description]);
    }else{
        [session setActive:YES error:nil];
    }
    self.session = session;
    NSLog(@"%@",session);
    NSLog(@"%@",self.session);
    //1.获取沙盒地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"path == %@",path);
    filePath = [path stringByAppendingString:@"/RRecord.wav"];
    NSLog(@"filePath == %@",filePath);
    //2.获取文件路径
    self.recordFileUrl = [NSURL fileURLWithPath:filePath];
    //设置参数
    NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                   //采样率  8000/11025/22050/44100/96000(影响音频的质量)
                                   [NSNumber numberWithFloat: 8000.0],AVSampleRateKey,
                                   // 音频格式 可以选择mp3格式 但是我选了。提示我不能使用
                                   [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                                   //采样位数  8、16、24、32 默认为16
                                   [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                   // 音频通道数 1 或 2
                                   [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                                   //录音质量
                                   [NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,
                                   nil];
    NSLog(@"%@",_recorder);
    /*初始化录音器 并且读取文件地址 */
    _recorder = [[AVAudioRecorder alloc] initWithURL:self.recordFileUrl settings:recordSetting error:nil];
    NSLog(@"%@",_recorder);
    if (_recorder) {
        /*级计量或放假默认是关闭的*/
        _recorder.meteringEnabled = YES;
        /*创建文件,准备记录。会自动记录*/
        [_recorder prepareToRecord];
        /*启动或恢复记录文件*/
        [_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");
    }
}
- (IBAction)stopRecord:(id)sender {
    [self removeTimer];
    NSLog(@"停止录音");
    NSLog(@"%@",self.recorder);
    if ([self.recorder isRecording]) {
        [self.recorder stop];
    }
    NSFileManager *manager = [NSFileManager defaultManager];
    NSLog(@"%@",manager);
    /*判断一个给定路劲是否为文件夹*/
    if ([manager fileExistsAtPath:filePath]){
        _noticeLabel.text = [NSString stringWithFormat:@"录了 %ld 秒,文件大小为 %.2fKb",COUNTDOWN - (long)countDown,[[manager attributesOfItemAtPath:filePath error:nil] fileSize]/1024.0];
    }else{
        _noticeLabel.text = @"最多录60秒";
    }
}
- (IBAction)PlayRecord:(id)sender {
    NSLog(@"播放录音");
    [self.recorder stop];
   // if ([self.player isPlaying])return;
    NSLog(@"%@",self.recordFileUrl);
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.recordFileUrl error:nil];
    NSLog(@"%li",self.player.data.length/1024);
    //此处需要恢复设置回放标志,否则会导致其它播放声音也会变小
    [self.session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [self.player play];
}
/**
 *  添加定时器
 */
- (void)addTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(refreshLabelText) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
/**
 *  移除定时器
 */
- (void)removeTimer
{
    [_timer invalidate];
    _timer = nil;
}
-(void)refreshLabelText{
    countDown --;
    _noticeLabel.text = [NSString stringWithFormat:@"还剩 %ld 秒",(long)countDown];
}
@end

AVAudioSession类由AVFoundation框架引入。每个IOS应用都有一个音频会话。这个会话可以被AVAudioSession类的sharedInstance类方法访问,如下:

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

在获得一个AVAudioSession类的实例后,你就能通过调用音频会话对象的setCategory:error:实例方法,来从IOS应用可用的不同类别中作出选择。下面列出了可供使用的音频会话类别:AVAudioSessionCategorySoloAmbient

这个类别非常像AVAudioSessionCategoryAmbient类别,除了会停止其他程序的音频回放,比如iPod程序。当设备被设置为静音模式,你的音频回放将会停止。

AVAudioSessionCategoryRecord这会停止其他应用的声音(比如iPod)并让你的应用也不能初始化音频回放(比如AVAudioPlayer)。在这种模式下,你只能进行录音。使用这个类别,调用AVAudioPlayer的prepareToPlay会返回YES,但是调用play方法将返回NO。主UI界面会照常工作。这时,即使你的设备屏幕被用户锁定了,应用的录音仍会继续。

AVAudioSessionCategoryPlayback这个类别会静止其他应用的音频回放(比如iPod应用的音频回放)。你可以使用AVAudioPlayer的prepareToPlay和play方法,在你的应用中播放声音。主UI界面会照常工作。这时,即使屏幕被锁定或者设备为静音模式,音频回放都会继续。

AVAudioSessionCategoryPlayAndRecord这个类别允许你的应用中同时进行声音的播放和录制。当你的声音录制或播放开始后,其他应用的声音播放将会停止。主UI界面会照常工作。这时,即使屏幕被锁定或者设备为静音模式,音频回放和录制都会继续。

AVAudioSessionCategoryAudioProcessing这个类别用于应用中进行音频处理的情形,而不是音频回放或录制。设置了这种模式,你在应用中就不能播放和录制任何声音。调用AVAPlayer的prepareToPlay和play方法都将返回NO。其他应用的音频回放,比如iPod,也会在此模式下停止。

AVAudioSessionCategoryAmbient这个类别不会停止其他应用的声音,相反,它允许你的音频播放于其他应用的声音之上,比如iPod。你的应用的主UI县城会工作正常。调用AVAPlayer的prepareToPlay和play方法都将返回YES。当用户锁屏时,你的应用将停止所有正在回放的音频。仅当你的应用是唯一播放该音频文件的应用时,静音模式将停止你程序的音频回放。如果正当iPod播放一手歌时,你开始播放音频,将设备设为静音模式并不能停止你的音频回放。

本人个人微信公众号地址(喜欢记得关注)


IOS之录音功能_第2张图片
辛小二个人微信公众号地址

你可能感兴趣的:(IOS之录音功能)