2011-05-23 38 views
1

我正在通过录制按钮录制iPhone麦克风的音频。我已经下载并掌握了Apple提供的样例项目(SpeakHere)。iOS录制音频并存储在播放列表中

但是,作为下一步,我想以“播放列表”样式保存用户(不使用iTunes播放列表,而使用本地播放列表)。

是否有可能使用Objective-C(与当前提供的C实现相对)执行此操作 - 理想情况下CoreData将用于存储音频。

感谢

回答

2

我是这样做的:

1)找到了SpeakHere代码创建临时文件 - 寻找在SpeakHereController类扩展的.caf。然后移动临时文件到你的应用程序目录,如下所示:

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)保存一些关于文件的元数据,至少是它的名字。我把那NSUserDefaults的成这样:

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)现在,你可以通过self.savedRecordings迭代显示保存录像的列表。

4)当用户选择一个录音时,您可以用选定的文件名轻松初始化一个AVAudioPlayer并播放它。

5)为了让用户删除的记录,你可以做这样的事情:

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"]; 

请注意,如果您的音频文件保存到文档文件夹,并启用“应用支持iTunes的文件共享”,在您的信息.plist,那么用户可以将他们的录音复制出应用程序并将其保存到他们的计算机中......如果您想要提供它,这是一个不错的功能。