如何使用Objective-C将audio数据保存到CoreData或从CoreData获取audio数据?

我是一个新的iOS开发。

如何使用Objective-C将audio数据保存到CoreData或从CoreData获取audio数据?

我只知道我必须使用NSData和二进制数据。

正如@shallowThought在他的评论中所说的,你通常不应该在Core Data中存储大的二进制数据对象。 将声音文件保存到应用程序的文档目录或其他沙箱目录之一,然后将文件的URL或path存储在Core Data中。

以为我会添加我用来完成我在上面评论中描述的代码。 这是迅速3.0(不ObjC,对不起)使用CoreData来存储audio录制(以及图像和video,虽然捕获这些更复杂,这里没有显示)。

我发现最好的方法是将logging捕获到文件中,然后将其转换为存储到数据库中的NSData值,再次将其作为二进制数据types,并允许CoreData使用外部存储。

stream程是首先调用setupAudio()创build一个单例audio会话,然后使用连接到UI上的button的startRecordAction()和stopRecordAction()方法来驱动会话(因此为sharedInstance表示法)。 虽然看起来像多个会话,但它只是一个共享的单例,这个结构让我可以在方法中分解使用这个实例的进程。

我已经简化了这个,所以停止方法在logging停止时自动将audiologging添加到数据库。 免责声明:我已经删除了一堆不适用于您的问题的代码,所以我可能已经添加了一个错误或丢弃了所需的东西,但是我认为它很接近。

代码如下:

 import AVFoundation ... var audioRecorder:AVAudioRecorder! let recordSettings = [AVSampleRateKey : NSNumber(value: Float(44100.0)), AVFormatIDKey : NSNumber(value: Int32(kAudioFormatMPEG4AAC)), AVNumberOfChannelsKey : NSNumber(value: 1), AVEncoderAudioQualityKey : NSNumber(value: Int32(AVAudioQuality.medium.rawValue))] func directoryURL() -> URL { let fileManager = FileManager.default let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask) let documentDirectory = urls[0] as NSURL let soundURL = documentDirectory.appendingPathComponent(“capturedAudio.m4a") return soundURL! } func setupAudio() { let audioSession = AVAudioSession.sharedInstance() do { unowned let myself = self try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord) try audioRecorder = AVAudioRecorder(url: myself.directoryURL(), settings: recordSettings) audioRecorder.prepareToRecord() } catch { logError... } } @IBAction func startRecordAction(_ sender: UIButton) { if !audioRecorder.isRecording { let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setActive(true) audioRecorder.record() } catch { logError... } } } @IBAction func stopRecordAction(_ sender: UIButton) { audioRecorder.stop() let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setActive(false) } catch { logError... } var audioTrack: Data? do { audioTrack = try Data(contentsOf: audioRecorder.url) } catch { logError... } addMediaCaptureToDB(audioTrack!, mediaType: "Recording") } func addMediaCaptureToDB(_ mediaData: Data, mediaType: String) { guard let newRec = NSEntityDescription.insertNewObject(forEntityName: "MediaCapture", into: context) as? MediaCapture else { logError... } newRec.mediaCapture = mediaData as NSData // Binary Data field / option set to allow External Storage newRec.type = mediaType newRec.captureDate = NSDate() newRec.uniqueID = String(Date().timeIntervalSince1970) // Save the new MediaCapture record to the database do { try context.save() } catch { logError... } } 

希望有帮助…