iOS实现录音转码MP3及转码BASE64上传示例

iOS 录音转码MP3及转码BASE64上传

一,开始录音

NSLog(@"开始录音");

[self startRecord];

- (void)startRecord
{
  //删除上次生成的文件,保留最新文件
  NSFileManager *fileManager = [NSFileManager defaultManager];
  if ([NSTemporaryDirectory() stringByAppendingString:@"myselfRecord.mp3"]) {
    [fileManager removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:@"myselfRecord.mp3"] error:nil];
  }
  if ([NSTemporaryDirectory() stringByAppendingString:@"selfRecord.wav"]) {
    [fileManager removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:@"selfRecord.wav"] error:nil];
  }
  
  //开始录音
  //录音设置
  NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
  //设置录音格式 AVFormatIDKey==kAudioFormatLinearPCM
  [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
  //设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量), 采样率必须要设为11025才能使转化成mp3格式后不会失真
  [recordSetting setValue:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];
  //录音通道数 1 或 2 ,要转换成mp3格式必须为双通道
  [recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
  //线性采样位数 8、16、24、32
  [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
  //录音的质量
  [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
  
  //存储录音文件
  recordUrl = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"selfRecord.wav"]];
  
  //初始化
  audioRecorder = [[AVAudioRecorder alloc] initWithURL:recordUrl settings:recordSetting error:nil];
  //开启音量检测
  audioRecorder.meteringEnabled = YES;
  audioSession = [AVAudioSession sharedInstance];//得到AVAudioSession单例对象

  if (![audioRecorder isRecording]) {
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];//设置类别,表示该应用同时支持播放和录音
    [audioSession setActive:YES error:nil];//启动音频会话管理,此时会阻断后台音乐的播放.
    
    [audioRecorder prepareToRecord];
    [audioRecorder peakPowerForChannel:0.0];
    [audioRecorder record];
  }
}

二,停止录音

[self endRecord];


 - (void)endRecord
 {
   [audioRecorder stop];             //录音停止
   [audioSession setActive:NO error:nil];     //一定要在录音停止以后再关闭音频会话管理(否则会报错),此时会延续后台音乐播放
 }

三,转码成MP3

- (void)transformCAFToMP3 {
  mp3FilePath = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"myselfRecord.mp3"]];
  
  @try {
    int read, write;
    
    FILE *pcm = fopen([[recordUrl absoluteString] cStringUsingEncoding:1], "rb");  //source 被转换的音频文件位置
    fseek(pcm, 4*1024, SEEK_CUR);                          //skip file header
    FILE *mp3 = fopen([[mp3FilePath absoluteString] 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, 11025.0);
    lame_set_VBR(lame, vbr_default);
    lame_init_params(lame);
    
    do {
      read = (int)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 {
    NSLog(@"MP3生成成功");
    base64Str = [self mp3ToBASE64];
  }
}

四,上传需要转码BASE64

 - (NSString *)mp3ToBASE64{
   NSData *mp3Data = [NSData dataWithContentsOfFile:[NSTemporaryDirectory() stringByAppendingString:@"myselfRecord.mp3"]];
   NSString *_encodedImageStr = [mp3Data base64Encoding];
   NSLog(@"===Encoded image:\n%@", _encodedImageStr);
   return _encodedImageStr;
 }

备注:其中可以直接生成的.caf  .wav    有压缩的MP3需要转格式,不能直接录音生成

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。