Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Note: Add AVFoundation framework to your project
- #pragma mark - .h file
- #import <AVFoundation/AVFoundation.h>
- // Implement this delegate : AVAudioRecorderDelegate
- AVAudioRecorder *recorder;
- #pragma mark - .m file
- // Configure audio recorder
- -(void)configureAudioRecorder {
- NSArray *searchPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentPath_ = [searchPaths objectAtIndex: 0];
- // Don't change the file extension
- NSString *soundFilePath = [documentPath_ stringByAppendingPathComponent:@"your_file_name_here.m4a"];
- NSURL *outputFileURL = [NSURL fileURLWithPath:soundFilePath];
- // Setup audio session
- AVAudioSession *session = [AVAudioSession sharedInstance];
- [session setCategory:AVAudioSessionCategoryRecord error:nil];
- [session setActive:YES error:nil];
- [session requestRecordPermission:^(BOOL granted) {
- if (granted) {
- // Define the recorder setting
- NSDictionary *recordSettings = @{AVFormatIDKey: @(kAudioFormatMPEG4AAC),
- AVEncoderAudioQualityKey: @(AVAudioQualityLow),
- AVNumberOfChannelsKey: @1,
- AVSampleRateKey: @22050.0f};
- // Initiate and prepare the recorder
- NSError *error;
- recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSettings error:&error];
- if (!error) {
- recorder.delegate = self;
- [recorder prepareToRecord];
- // Start recording
- [recorder record];
- NSLog(@"Record Start");
- } else {
- NSLog(@"%@", error.description);
- }
- } else {
- NSLog(@"Permission to record audio denied");
- }
- }];
- }
- // Call "configureAudioRecorder" in your record button
- // In your "pause/stop" button call
- AVAudioSession *audioSession = [AVAudioSession sharedInstance];
- [audioSession setActive:NO error:nil];
- [recorder stop];
- // Implement the delegate method
- -(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag {
- // if flag param equals to YES your file is saved successfull in : avrecorder.url.absoluteString
- }
- // ===================================================================================================== //
- // To Play File Saved after Recording
- AVAudioSession *session = [AVAudioSession sharedInstance];
- [session setCategory:AVAudioSessionCategoryPlayback error:nil];
- [session setActive:YES error:nil];
- NSURL *filePath = [NSURL URLWithString:@"path to your saved file. ex: avrecorder.url.absoluteString"];
- AVPlayer *avPlayer = [AVPlayer playerWithURL:filePath];
- AVPlayerViewController *controller = [[AVPlayerViewController alloc] init];
- controller.player = avPlayer;
- [self presentViewController:controller animated:YES completion:^{
- [avPlayer play];
- }];
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement