iOS 运用AVAudioRecorder、AVAudioPlayer实现简单的录音与播放

今天我们来说一下如何实现录音与播放功能。AVAudioRecorder这个类可用来实现录音的采集,而我们用AVAudioPlayer则可实现录音的播放。首先记得导入#import

我的做法是自己写了个类,重写了init方法,稍微封装了一下。你也可以在controller中直接用。 废话不多说,上代码:

- (id)init {
    
    if (self = [super init]) {
   NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];
  //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
  [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatAppleIMA4] 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];
 
  //文件存放路径       
   _url = [NSURL URLWithString:[self getFilePath]];
        
   _recorder = [[AVAudioRecorder alloc]initWithURL:_url settings:recordSetting error:nil];
   AVAudioSession *audioSession = [AVAudioSession sharedInstance];
   [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
   [audioSession setActive:YES error:nil];
   //_recorder.meteringEnabled = YES;
   //设置录音时长,超过这个时间后,会暂停单位是秒
   //[_recorder recordForDuration:30];
   //准备录音
    [_recorder prepareToRecord];
    }
    
    return self;
}

- (NSString *)getFilePath {
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *urlPath = [path stringByAppendingPathComponent:@"123.caf"];
    
    return urlPath;
}
//录音开始
- (void)beginSoundRecording {
    
    [_recorder record];
}
//录音暂停
- (void)pauseSoundRecording {
    
    [_recorder pause];
}
//录音结束
- (void)stopSoundRecording {
    
    [_recorder stop];
}

播放的代码:

- (void)beginPlay {
    
    if (_url) {
        
        _player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:[self getFilePath]] error:nil];
        //设置播放循环次数
        //[_player setNumberOfLoops:0];
        //音量,0-1之间
        //[_player setVolume:1];
        [_player prepareToPlay];
        //开始播放
        [_player play];
    }
}
 - (void)resumePlay {

   //暂停之后恢复播放
    [_player play];
}

- (void)pausePlay {
    //暂停播放
    [_player pause];
}

录音出来的通常是caf pcm格式,文件较大,而且在其他设备上还可能无法播放,可以使用lame进行mp3转码:

- (NSString *)mp3FilePath {
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *urlPath = [path stringByAppendingPathComponent:@"123.mp3"];
    
    return urlPath;
}

//转为Mp3
- (NSString *)audioCAFtoMP3 {
    
    NSString *cafFilePath = [self getFilePath];
    
    NSString *mp3FilePath = [self mp3FilePath];
    
    @try {
        int read, write;
        
        FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source 被转换的音频文件位置
        fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header
        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output 输出生成的Mp3文件位置
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        
        lame_set_in_samplerate(lame, 44100.0);
        lame_set_VBR(lame, vbr_default);
        
        lame_set_brate(lame,8);
        
        lame_set_mode(lame,3);
        
        lame_set_quality(lame,2);
        
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
    }
    @finally {
        
        return mp3FilePath;
    }
}

功能代码差不多就这些,UI界面大家各抒己见。
下面是一份带UI界面功能实现的Demo,有兴趣的可以看一下:

https://github.com/WisdomWang/SoundRecordDemo

你可能感兴趣的:(iOS 运用AVAudioRecorder、AVAudioPlayer实现简单的录音与播放)