• 录音


    使用AVAudioRecorder录制音频数据

    1. 包含头文件#import <AVFoundation/AVFoundation.h>

    2. 创建属性:录音对象、播放对象、存放录音文件的URL

    @property (nonatomic, strong) AVAudioRecorder *recorder;
    @property (nonatomic, strong) AVAudioPlayer *player;
    @property (nonatomic, strong) NSURL *recordURL; 

    3. 设置支持AVAudioSession支持录音和回放功能

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

    4. 录音前准备和设置工作

        NSMutableDictionary *setting = [NSMutableDictionary dictionary];
        
        // 编码格式
        setting[AVFormatIDKey] = @(kAudioFormatAppleIMA4);
        // 采样率
        setting[AVSampleRateKey] = @(44100);
        // 声道数
        setting[AVNumberOfChannelsKey] = @2;
        // 量化位数
        setting[AVLinearPCMBitDepthKey] = @16;
        // 编码质量
        setting[AVEncoderAudioQualityKey] = @(AVAudioQualityHigh);
        
        NSError *error;
        _recorder = [[AVAudioRecorder alloc] initWithURL:self.recordURL settings:setting error:&error];
        
        if (error != nil) {
            NSLog(@"error >>> %@", error);
        }
        // 准备录制
        [_recorder prepareToRecord];

    5. 懒加载

    - (NSURL *)recordURL
    {
        if (_recorder == nil) {
            NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
            //当使用kAudioFormatAppleIMA4编码格式时,生成的文件格式为caf
            NSString *path = [docPath stringByAppendingPathComponent:@"test.caf"];
            
            _recordURL = [NSURL URLWithString:path];
        }
        return _recordURL;
    }
    
    - (AVAudioPlayer *)player
    {
        if (_player == nil) {
            _player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.recordURL error:nil];
            _player.numberOfLoops = 1;
            
            [_player prepareToPlay];
        }
        return _player;
    }

    6. 录音/播放控制

    - (IBAction)startRecord:(UIButton *)sender {
        [_recorder record];  //开始录音
    }
    - (IBAction)startPlay:(UIButton *)sender {
        [self.player play];  //开始播放
    }
    - (IBAction)endRecord:(UIButton *)sender {
        
        [_recorder stop];    //结束录音
    }
    - (IBAction)endPlay:(UIButton *)sender {
        [self.player stop];  //停止播放
    }
  • 相关阅读:
    如何使用wei-ui框架,wei-ui框架有哪些组件
    微信小程序tabbar如何配置
    如何使用promise封装wx.request()、
    微信有哪些小程序内置组件,目录结构
    uni-app生命周期
    vue任意关系组件通信与跨组件监听状态 vue-communication
    vue父子组件状态同步的最佳方式续章(v-model篇)
    webstorm中emmet展开a标签和行内元素不换行的解决办法
    深入理解 vue 中 scoped 样式作用域的规则
    javascript事件环微任务和宏任务队列原理
  • 原文地址:https://www.cnblogs.com/10-19-92/p/4865863.html
Copyright © 2020-2023  润新知