2011-05-23 79 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,那麼用戶可以將他們的錄音複製出應用程序並將其保存到他們的計算機中......如果您想要提供它,這是一個不錯的功能。