Phone recording AVAudioRecorder, and converted to MP3 format

Apple provides a AVAudioRecorder class to allow us to audio recording, recording is very convenient!
in the use of AVAudioRecorder to do some preparation before recording,
1, iOS10 and above, call the system function to add the corresponding key in the info.plist file, as shown in figure Key:, adding Privacy – Microphone Usage Description in the info.plist file, the Value value can not write well!

Phone recording AVAudioRecorder, and converted to MP3 format

Second, the authority verification, the following code:

AVAudioSession *session = [AVAudioSession sharedInstance]; if ([session respondsToSelector:@selector (requestRecordPermission:)] [session) {performSelector:@selector (requestRecordPermission:) withObject:^ (BOOL granted) {if (granted) {/ / the user agrees to obtain the microphone, must perform the UI operation in the main thread!!! Dispatch_queue_t queueOne = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async (queueOne, dispatch_async ^{(dispatch_get_main_queue), UI (^{/ execution in the main thread, here is the implementation of recording and timing operation of the UI [self record];});});} else {/ / the user does not agree with the acquisition UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@ "microphone the microphone is not available" message:@ "in the" Settings - Privacy - Microphone "allow XXX to access your microphone" preferredStyle:UIAlertControllerStyleAlert]; *openAction = UIAlertAction [UIAlertAction actionWithTitle:@ "to open" style:UIAlertActionStyleDefault handler:^ (UIAlertAction * _Nonnull action) {/ / if you want to jump directly to the user interface settings, you can perform the following operation, if not required, just ignore the following code / * *iOS10 Apple began to jump directly to ban the use of single system settings page, only jump to apply all of the settings page you can add a single path following *iOS10 system settings, and add the URL Type in info, URL schemes will set the path to prefs. *@ "prefs:root=Sounds" * / NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; if ([[UIApplication sharedApplication] canOpenURL:url]) {[[UIApplication sharedApplication] openURL:url]}}]; [alertController addAction:; openAction] [self; presentViewController:alertController animated:YES completion:nil];}}}];

3 up, in order to know you are recording, must have a recording timer!
first make a label display time

- (void addTimerLabel) {/ / this is a method of creating label's own package! _timerLabel [CommonLib = createLabelFrame:CGRectMake (20, 120, kScreenWidth - 40, TimerLabelH) text:@ "00:00:00" alignment:NSTextAlignmentCenter textColor:[UIColor greenColor] font:TimerLabelH]; [self.view addSubview:_timerLabel];} / / to the timing of course, timer, timer set here updates per second, because here the minimum time unit is seconds, if the minimum time in milliseconds, to 1 instead, 0.01! This method is called when you click on the record - (void) startTimer [NSTimer scheduledTimerWithTimeInterval:1.0 target:self {_timer = selector:@selector (updateSecond:) userInfo:nil repeats:YES];} / / update UI operations per second (void) - updateSecond: (NSTimer * timer) {_second + +; if (_second = = 1) {[self enbleBtn];} / / this is the time when the display is displayed in the label NSString *timerStr [self = convertTimeToString:_second]; _timerLabel.text = timerStr;} / / time format specification - (NSString) convertTimeToString: (NSInteger) second NSDateFormatter [[NSDateFormatter alloc] init] {*formatter = [formatter; setDateFormat:@ "HH:mm:ss"]; NSDate *date = [formatter dateFro MString:@ "00:00:00"]; date = [date dateByAddingTimeInterval:second]; NSString *timeString = [formatter stringFromDate:date]; return timeString;}

Well, the above steps are completed, you can start recording operation!

/ / set playing in the background, this is a recording and playback recording set _session = [AVAudioSession sharedInstance]; NSError *sessionError; [_session setCategory:AVAudioSessionCategoryPlayAndRecord error:& sessionError]; / / there is no judgment background playing if (_session = = Nil) {SIMEILog (@ "Error creating sessing:%@", [sessionError description]);} else {/ / close other audio playback, set oneself for the active state of [_session setActive:YES error:nil];} if ([_timer! IsValid]) {[self startTimer];} else {/ / this method is to write a NSTimer extension class Category, specific methods attached code [_timer continueTimer] below AVAudioRecorder if;} / / set {NSDictionary *setti (self.recorder!) NGS = @{AVFormatIDKey (kAudioFormatLinearPCM, AVSampleRateKey): @: @ (11025), AVNumberOfChannelsKey: @2, AVEncoderBitDepthHintKey: @16, AVEncoderAudioQualityKey: @ (AVAudioQualityHigh)}; / / to the recording, will have access to audio recordings to the file _recordUrl file path storage recording, attached to the self.recorder alloc] initWithURL:_recordUrl settings:settings [[AVAudioRecorder = error:nil] in the following settings; / * * parameter 1.AVNumberOfChannelsKey channel number usually double channel sampling rate value of 2 2.AVSampleRateKey unit HZ is usually set to 44100 is 44.1k, the sampling rate must be set to 11025 to make it into the MP3 format will not 3.AVLinearPCMBitDepthKey bit rate distortion 8162432 4.AVEncoderAudioQualityKey sound quality AVAudioQualityMin = 0, AVAudioQualityLow = 0x20, minimum quality, low quality of the AVAudioQualityMedium = 0x40, AVAudioQualityHigh = 0x60 in the middle of the quality, the quality of the high rate of AVAudioQualityMax = 0x7F the best quality 5.AVEncoderBitRateKey audio encoding bit rate Kbps transmission is generally set up 128000 128kbps * /} / / for recording [_recorder prepareToRecord]; / / open meter counting function, this function must be open, in order to detect audio value [_recorder setMeteringEnabled:YES]; / / start or resume recording. Audio file [_recorder record];

The following is attached to the Category NSTimer, how to create Category, right click New -&gt Files; ObjectC – -> File Type select Category, Class select NSTimer, File file name of their own random access

Add two methods / / in the.H file pause time - (void) pauseTimer; / / - (void) continueTimer to time; to implement two methods in the.M file - pauseTimer (void) {/ / if return has been released! IsValid if ([self isValid] corresponding to invalidate! Return); / / starting time was long after [self setFireDate:[NSDate distantFuture]] (void);} - continueTimer {if ([self! IsValid]) return; / / [self setFireDate:[NSDate date is now starting time ";}

Attach _recordUrl path creation

/ / for recording file is relatively large, so we put it in an Temp file, Temp will automatically delete the files in the _recordFilePath = [NSTemporaryDirectory when the restart of the app (stringByAppendingPathComponent:) @ "record.caf"]; / / create a temporary file to store the recording file = [NSURL fileURLWithPath:self.recordFilePath] _recordUrl;

Now we have to turn the recording file into MP3 format, and a lot of ways to check the Internet and found that most people are recommended to use lame to convert mp3!
so the following is attached to the method of lame conversion MP3, lame download link GitHub

After the download is completed into the process, under the Build Phases under Link With Library add lame

Phone recording AVAudioRecorder, and converted to MP3 format

after the introduction of the general Library Search Paths will automatically add the lame file in the project path, if not added, add their own manual, otherwise it will be wrong!!!

After the success of the introduction, began to use the lame conversion MP3, a large section of the C code, C language, a good student to look at the more handy

The first #import "lame.h" / / then start writing code conversion / / if you want to save myself down, will save to MP3 to Document, the following code, if not, then saved to the Temp file NSString *fileName [NSString stringWithFormat:@ = "/%@.mp3", nowTime] NSString *filePath ([[NSHomeDirectory); stringByAppendingFormat:@ = "/Documents/" stringByAppendingPathComponent:fileName]; _mp3Url = [NSURL URLWithString:filePath]; @try write; FILE read {int, *pcm = fopen ([_recordFilePath, cStringUsingEncoding:1], RB); audio files are converted to //source fseek (PCM, 4 * 1024, SEEK_CUR); / / delete head, otherwise there will be noise in a second before FILE ([filePath *mp3 = fopen cStringUsingEncoding:1], "WB"); / / The output of the output generated const Mp3 file location int PCM_SIZE = 8192; const int MP3_SIZE = 8192; short int pcm_buffer[PCM_SIZE * 2] unsigned char; mp3_buffer[MP3_SIZE]; / / here we must note that the configuration of the lame to AVAudioRecorder configuration is consistent, otherwise it will cause the conversion was not successful lame_t = lame_init (lame); lame_set_in_samplerate (lame, 11025) sampling rate; / / 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 (lame, lame_encode_buffer_interleaved = write 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 to generate success!!! ");}

Well, the above is the main record and turn the MP3 code, and finally say, this demo upload GitHub when a little problem, so if you want to demo students to stay in the mailbox! If there is any help to you, with a good oh!!!