Last active
August 29, 2015 14:10
-
-
Save mthongvanh/c26813e45771c93d054d to your computer and use it in GitHub Desktop.
via #iphonedev on irc.freenode.net: AVAudioRecorder failed to initialize by crashing on initialization method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Problem: AVAudioRecorder failed to initialize by crashing on initialization method | |
// Diagnosis: NSURL *audioURL was nil at audioRecorder initiliazation point because audioURL's weak declaration | |
// Solution: Declare NSURL *audioURL as strong to ensure it does not get deallocated prematurelys. | |
// *Side note suggestion: Be sure to use [AVAudioRecorder record] instead of prepareToRecord since record will call it implicitly | |
// and handle errors appropriately! | |
// properties | |
// @property (weak, nonatomic) NSURL *audioURL; /* User's original declaration */ | |
@property (strong, nonatomic) NSURL *audioURL; | |
@property (strong, nonatomic) AVAudioRecorder *audioRecorder; | |
@synthesize audioURL = audioURL; | |
@synthesize audioRecorder = audioRecorder; | |
// implementation | |
- (void)viewDidLoad { | |
[super viewDidLoad]; | |
// Do any additional setup after loading the view. | |
NSLog(@"FILE PATH :%@", NSTemporaryDirectory()); | |
// set audio file | |
NSArray *pathComponents = [NSArray arrayWithObjects: | |
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], | |
@"MyAudioMemo.m4a", | |
nil]; | |
audioFileURL = [NSURL fileURLWithPathComponents:pathComponents]; | |
// audio session | |
AVAudioSession *session = [AVAudioSession sharedInstance]; | |
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]; | |
[session setActive:YES error:nil]; | |
NSDictionary *audioSettings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:44100],AVSampleRateKey,[NSNumber numberWithInt:kAudioFormatAppleLossless], AVFormatIDKey, [NSNumber numberWithInt:1],AVNumberOfChannelsKey, [NSNumber numberWithInt:AVAudioQualityMedium], AVEncoderAudioQualityKey, nil]; | |
audioRecorder = [[AVAudioRecorder alloc] initWithURL:audioFileURL settings:audioSettings error:nil]; | |
audioRecorder.delegate = self; | |
audioRecorder.meteringEnabled = YES; | |
[audioRecorder prepareToRecord]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment