【问题标题】:iOS Record audio and store in playlistiOS 录制音频并存储在播放列表中
【发布时间】:2011-05-23 15:05:10
【问题描述】:

我希望通过录制按钮从 iPhone 麦克风录制音频。我已经下载并掌握了 Apple 提供的示例项目 (SpeakHere)。

但是,下一步,我想将用户录制的内容保存为“播放列表”样式(不使用 iTunes 播放列表,而是使用本地播放列表)。

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

谢谢

【问题讨论】:

    标签: objective-c ios audio playlist


    【解决方案1】:

    我是这样做的:

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

    请注意,如果您将音频文件保存到 Documents 文件夹并在 info.plist 中启用“应用程序支持 iTunes 文件共享”,那么用户可以将他们的录音从应用程序中复制出来并保存到他们的计算机上......不错的功能,如果你想提供的话。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      相关资源
      最近更新 更多