使用lame转换音频时遇到的杂音问题

最近项目增加了录音功能,ios端需要将WAV格式音频转换成MP3然后上传到服务器,项目中用到了lame,音频转换都成功了,但是出现了杂音的问题,经过查资料和自己研究解决了问题,新手发表,有错误请多指教。。。。。

录音代码:

 _setting = [[NSDictionary alloc] initWithObjectsAndKeys:

             [NSNumber numberWithFloat: 15000],AVSampleRateKey, //采样率

             [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,

             [NSNumber numberWithInt: 2], AVNumberOfChannelsKey,//通道

             [NSNumber numberWithInt: AVAudioQualityMedium],AVEncoderAudioQualityKey,//音频编码质量

                                 nil];


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

  [[AVAudioSession sharedInstance] setActive:YES error:nil];

  NSError *error=nil;

  _recorder = [[AVAudioRecorder alloc] initWithURL:pathUrl

                                          settings:_setting

                                             error:&error];

  [_recorder prepareToRecord];

  _recorder.meteringEnabled = YES; //设置可以检测音量变化

  [_recorder record];


转换代码:

+ (NSString *)audioToMP3: (NSString *)sourcePath isDeleteSourchFile:(BOOL)isDelete{

  NSString *inPath = sourcePath;

  NSFileManager *fm = [NSFileManager defaultManager];

  if (![fm fileExistsAtPath:sourcePath]){

    NSLog(@"file path error!");

    return @"";

  }

  NSString *outPath = [[sourcePath stringByDeletingPathExtension] stringByAppendingString:@".mp3"];

  @try {

    int read, write;

    FILE *pcm = fopen([inPath cStringUsingEncoding:1], "rb");

    fseek(pcm, 4*1024, SEEK_CUR);

    FILE *mp3 = fopen([outPath cStringUsingEncoding:1], "wb");

    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_VBR(lame, vbr_default);

    lame_set_num_channels(lame,2);//默认为2双通道

    lame_set_in_samplerate(lame, 20000);//11025.0

    lame_set_brate(lame,8);

    lame_set_mode(lame,3);

    lame_set_quality(lame,5); /* 2=high 5 = medium 7=low 音质*/

    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 build success!");

    if (isDelete) {

      NSError *error;

      [fm removeItemAtPath:sourcePath error:&error];

      if (error == nil){

        NSLog(@"source file is deleted!");

      }

    }

    return outPath;

  }

}


首先录音的时候和转换的时候必须都是双通道,还要就是查资料的时候说的是采样率必须一致,开始的时候设置的一样的,一致有杂音,而且语速也会有问题,后来调节了一下采样率没有了杂音,但是发现录音和转换的时候采样率不一样也可以,不知其所以然,高手请指教。。。。。。




你可能感兴趣的:(iOS,音频)