iOS Implementation of Recording Transcoding MP3 and Transcoding BASE64 Upload Example

  • 2021-11-10 11:04:59
  • OfStack

iOS recording transcoding MP3 and transcoding BASE64 uploading

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:@"selfRecord.wav"]) {
    [fileManager removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:@"selfRecord.wav"] error:nil];
  }
  
  // Start recording 
  // Recording settings 
  NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
  // Format recording  AVFormatIDKey==kAudioFormatLinearPCM
  [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
  // Set the recording sampling rate (Hz)  Such as: AVSampleRateKey==8000/44100/96000 (Affects audio quality) ,  The sampling rate must be set to 11025 To transform into mp3 Format will not be distorted 
  [recordSetting setValue:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];
  // Number of recording channels  1  Or  2  To convert to mp3 Format must be dual channel 
  [recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
  // Linear sampling number  8 , 16 , 24 , 32
  [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
  // Quality of recording 
  [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
  
  // Store recording files 
  recordUrl = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"selfRecord.wav"]];
  
  // Initialization 
  audioRecorder = [[AVAudioRecorder alloc] initWithURL:recordUrl settings:recordSetting error:nil];
  // Turn on volume detection 
  audioRecorder.meteringEnabled = YES;
  audioSession = [AVAudioSession sharedInstance];// Get AVAudioSession Singleton object 

  if (![audioRecorder isRecording]) {
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];// Set categories , Indicates that the application supports both playback and recording 
    [audioSession setActive:YES error:nil];// Start audio session management , This will block the playing 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];     //1 Be sure to turn off audio session management after recording stops (otherwise an error will be reported), and the background music will continue at this time 
 }

3. Transcoding into MP3


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

4. Upload requires transcoding BASE64


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

Remarks: Among them, caf. wav can be generated directly. There are compressed MP3 that need to be converted into format, and cannot be generated directly by recording


Related articles: