Reputation: 11
I'm looking to record audio from the iPhone microphone via a record button. I have downloaded and got to grips with the sample project Apple provides to do this (SpeakHere).
However as a next step, I'd like to save the users recording in a "playlist" style (not using the iTunes playlist, rather a local playlist).
Is it possible to do this using Objective-C (as opposed to the C implementation currently provided) - ideally CoreData would be used to store the audio.
Thanks
Upvotes: 1
Views: 2115
Reputation: 9061
Here's how I did it:
1) Find the temp file that the SpeakHere code creates -- look for the .caf extension in the SpeakHereController class. Then move that temp file to your application directory with something like this:
NSString *myFileName = @"MyName"; // this would probably come from a user text field
NSString *tempName = @"recordedFile.caf";
NSString *saveName = [NSString stringWithFormat:@"Documents/%@.caf", myFileName];
NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:tempName];
NSString *savePath = [NSHomeDirectory() stringByAppendingPathComponent:saveName];
2) Save some metadata about the file, at least its name. I'm putting that into NSUserDefaults like this:
NSDictionary *recordingMetadata = [NSDictionary dictionaryWithObjectsAndKeys:
myFileName, @"name",
[NSDate date], @"date",
nil];
[self.savedRecordings addObject:recordingMetadata]; // savedRecordings is an array I created earlier by loading the NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:self.savedRecordings forKey:@"recordings"]; // now I'm updating the NSUserDefaults
3) Now you can display a list of saved recordings by iterating through self.savedRecordings.
4) When the user selects a recording, you can easily initialize an AVAudioPlayer with the selected file name and play it back.
5) To let users delete recordings, you can do something like this:
NSString *myFileName = @"MyName";
// delete the audio file from the application directory
NSString *fileName = [NSString stringWithFormat:@"Documents/%@.caf", myFileName];
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] removeItemAtPath:filePath error:NULL];
// delete the metadata from the user preferences
for (int i=0; i<[self.savedRecordings count]; i++) {
NSDictionary *thisRecording = [self.savedRecordings objectAtIndex:i];
if ([myFileName isEqualToString:[thisRecording objectForKey:@"name"]]) {
[self.savedRecordings removeObjectAtIndex:i];
break;
}
}
[[NSUserDefaults standardUserDefaults] setObject:self.savedRecordings forKey:@"recordings"];
Note that if you save the audio files into the Documents folder and enable "Application supports iTunes file sharing" in your info.plist, then users can copy their recordings out of the app and save them onto their computers ... a nice feature if you want to offer it.
Upvotes: 2