SoFunction
Updated on 2025-04-12

iOS implementation of recording and transcoding MP3 and transcoding BASE64 upload example

iOS recording and transcoding MP3 and transcoding BASE64 upload

1. Start recording

NSLog(@"Start recording");

[self startRecord];

- (void)startRecord
{
  //Delete the last generated file and keep the latest file  NSFileManager *fileManager = [NSFileManager defaultManager];
  if ([NSTemporaryDirectory() stringByAppendingString:@"myselfRecord.mp3"]) {
    [fileManager removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:@"myselfRecord.mp3"] error:nil];
  }
  if ([NSTemporaryDirectory() stringByAppendingString:@""]) {
    [fileManager removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:@""] error:nil];
  }
  
  //Start recording  //Recording settings  NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
  //Set recording format AVFormatIDKey==kAudioFormatLinearPCM  [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
  //Set the recording sampling rate (Hz). For example: AVSampleRateKey==8000/44100/96000 (affects the quality of the audio). The sampling rate must be set to 11025 to make it not distorted after conversion to mp3 format.  [recordSetting setValue:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];
  //The number of recording channels is 1 or 2. To convert to mp3 format, it must be dual-channel.  [recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
  //The number of linear sampling bits 8, 16, 24, 32  [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
  //The quality of recording  [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
  
  //Storage recording files  recordUrl = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@""]];
  
  //initialization  audioRecorder = [[AVAudioRecorder alloc] initWithURL:recordUrl settings:recordSetting error:nil];
  // Turn on volume detection   = YES;
  audioSession = [AVAudioSession sharedInstance];//Get the AVAudioSession singleton object
  if (![audioRecorder isRecording]) {
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];//Set the category, which means that the application supports both playback and recording    [audioSession setActive:YES error:nil];//Start audio session management, which will block the playback of background music.    
    [audioRecorder prepareToRecord];
    [audioRecorder peakPowerForChannel:0.0];
    [audioRecorder record];
  }
}

2. Stop recording

[self endRecord];


 - (void)endRecord
 {
   [audioRecorder stop];             //Recording stops   [audioSession setActive:NO error:nil];     //Be sure to turn off audio session management after recording is stopped (otherwise an error will be reported), and the background music playback will be continued at this time. }

3. Transcode into MP3

- (void)transformCAFToMP3 {
  mp3FilePath = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"myselfRecord.mp3"]];
  
  @try {
    int read, write;
    
    FILE *pcm = fopen([[recordUrl absoluteString] cStringUsingEncoding:1], "rb");  //source The converted audio file location    fseek(pcm, 4*1024, SEEK_CUR);                          //skip file header
    FILE *mp3 = fopen([[mp3FilePath absoluteString] cStringUsingEncoding:1], "wb"); //output output output the generated Mp3 file location    
    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 generation successfully");
    base64Str = [self mp3ToBASE64];
  }
}

Fourth, uploading requires transcoding BASE64

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

Note: .caf  .wav     MP3 that can be directly generated needs to be converted to format and cannot be directly recorded and generated.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.