欢迎来到代码驿站!

iOS代码

当前位置:首页 > 移动开发 > iOS代码

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

时间:2020-11-06 10:21:49|栏目:iOS代码|点击:

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需要转格式,不能直接录音生成

上一篇:iOS本地推送简单实现代码

栏    目:iOS代码

下一篇:iOS开发中使用UIDynamic来捕捉动画组件的重力行为

本文标题:iOS实现录音转码MP3及转码BASE64上传示例

本文地址:http://www.codeinn.net/misctech/19713.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有