Recording is performed on ios devices. The format of the recording file is caf. However, this format cannot be played on many devices. To adapt to the playback function of the terminal, caf is converted to an mp3 file.
When recording a caf file, you must use a dual channel. Otherwise, the audio is incorrect when the file is converted to MP3 format. Set the caf recording end:
NSMutableDictionary * recordSetting = [NSMutableDictionary dictionary];
[RecordSetting setValue: [NSNumber numberWithInt: kAudioFormatLinearPCM] forKey: AVFormatIDKey]; //
[RecordSetting setValue: [NSNumber numberWithFloat: 8000.0] forKey: AVSampleRateKey]; // Sampling Rate
[RecordSetting setValue: [NSNumber numberWithInt: 2] forKey: AVNumberOfChannelsKey]; // sound channel, which must be a two-channel
[RecordSetting setValue: [NSNumber numberWithInt: AVAudioQualityLow] forKey: AVEncoderAudioQualityKey]; // audio quality
The code for converting mp3 files is:
NSString * cafFilePath = cafFilePathName; // caf file path
NSString * mp3FilePath = mp3FilePathName; // path for storing mp3 files
NSFileManager * fileManager = [NSFileManager defaultManager];
If ([fileManager removeItemAtPath: mp3FilePath error: nil])
{
NSLog (@ "delete ");
}
@ Try {
Int read, write;
FILE * pcm = fopen ([cafFilePath cStringUsingEncoding: 1], "rb"); // location of the audio FILE to which the source is converted
If (pcm = NULL)
{
NSLog (@ "file not found ");
}
Else
{
Fseek (pcm, 4*1024, SEEK_CUR); // skip file header
FILE * mp3 = fopen ([mp3FilePath cStringUsingEncoding: 1], "wb"); // output the location of the generated Mp3 FILE
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_num_channels (lame, 1); // you can specify 1 as a single channel. The default value is 2.
Lame_set_in_samplerate (lame, 8000.0); // 11025.0
// Lame_set_VBR (lame, vbr_default );
Lame_set_brate (lame, 8 );
Lame_set_mode (lame, 3 );
Lame_set_quality (lame, 2);/* 2 = high 5 = medium 7 = low sound quality */
Lame_init_params (lame );
Do {
Read = 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 );
Return YES;
}
Return NO;
}
@ Catch (NSException * exception ){
NSLog (@ "% @", [exception description]);
Return NO;
}
@ Finally {
NSLog (@ "execution completed ");
}