IOS之录音功能

作者: 辛小二 | 来源:发表于2017-04-13 15:56 被阅读1086次
第一步导入头文件

首先导入头文件#import <AVFoundation/AVFoundation.h>和#import "lame.h"


导入录音的头文件

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

<!-- 相册 -->
    <key>NSPhotoLibraryUsageDescription</key>
    <string>App需要您的同意,才能访问相册</string>
    <!-- 相机 -->
    <key>NSCameraUsageDescription</key>
    <string>App需要您的同意,才能访问相机</string>
    <!-- 麦克风 -->
    <key>NSMicrophoneUsageDescription</key>
    <string>App需要您的同意,才能访问麦克风</string>
    <!-- 位置 -->
    <key>NSLocationUsageDescription</key>
    <string>App需要您的同意,才能访问位置</string>
    <!-- 在使用期间访问位置 -->
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>App需要您的同意,才能在使用期间访问位置</string>
    <!-- 始终访问位置 -->
    <key>NSLocationAlwaysUsageDescription</key>
    <string>App需要您的同意,才能始终访问位置</string>
    <!-- 日历 -->
    <key>NSCalendarsUsageDescription</key>
    <string>App需要您的同意,才能访问日历</string>
    <!-- 提醒事项 -->
    <key>NSRemindersUsageDescription</key>
    <string>App需要您的同意,才能访问提醒事项</string>
    <!-- 运动与健身 -->
    <key>NSMotionUsageDescription</key> <string>App需要您的同意,才能访问运动与健身</string>
    <!-- 健康更新 -->
    <key>NSHealthUpdateUsageDescription</key>
    <string>App需要您的同意,才能访问健康更新 </string>
    <!-- 健康分享 -->
    <key>NSHealthShareUsageDescription</key>
    <string>App需要您的同意,才能访问健康分享</string>
    <!-- 蓝牙 -->
    <key>NSBluetoothPeripheralUsageDescription</key>
    <string>App需要您的同意,才能访问蓝牙</string> 
    <!-- 媒体资料库 --> 
    <key>NSAppleMusicUsageDescription</key> 
    <string>App需要您的同意,才能访问媒体资料库</string>
第三步 初始化播放器 录音器 文件地址 定时器 这些控件
@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 <AVFoundation/AVFoundation.h>
#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之录音功能

    第一步导入头文件 首先导入头文件#import 和#import "lame.h" #######第二步 写访问...

  • iOS 录音功能

    https://www.jianshu.com/p/c1bdab0ddf59[https://www.jiansh...

  • iOS 录音功能

    音频基本知识 采样率(sampleRate)所谓采样就是在时间轴上对信号进行数字化。根据奈奎斯特定理(也称为采样定...

  • iOS中录音功能

    应用场景 在即时通讯APP中,例如微信,QQ,等都有语音发送功能,一般都要先将录音录制下来才能发送录音。 音频相关...

  • 关于iOS 录音功能

    啥也不说,直接上代码,复制即可 首先要引进系统包​CoreGraphics.framework Foundat...

  • iOS实现录音功能

    ps:文章内容的代码部分,由于不便暴露业务逻辑,可能会有部分删减,但是主体功能基本保留 背景 这段时间应公司业务需...

  • iOS 实现录音功能

    参考资料 https://www.jianshu.com/p/fb7dfb033989 音频文件相关知识 文件格式...

  • iOS 实现录音功能

    #pragma mark ===== 录制音频初始化 -(void)saveAudio{ AVAudioSes...

  • 随记一些文章链接[不仅仅是音视频的]

    iOS录音方法实用详解(配Demo下载)iOS开发系列--音频播放、录音、视频播放、拍照、视频录制深入浅出GCD之...

  • iOS之录音

    介绍 录音使用的也是AVFoundation框架相关类:AVAudioRecorder可以设置的一些属性 :<1>...

网友评论

  • c77f4a115d4f:播放音频时必须停止录制么,暂停录制可以么

本文标题:IOS之录音功能

本文链接:https://www.haomeiwen.com/subject/moebattx.html