gpt4 book ai didi

swift - 如何在CloudKit中存储音频文件以及如何从中获取音频文件?

转载 作者:行者123 更新时间:2023-12-03 01:18:02 25 4
gpt4 key购买 nike

我正在尝试记录语音消息并将其作为CKAsets存储在CloudKit上。我将它们转换为AVAudioFile并将它们保存为Post记录中的多个属性之一到CloudKit。

var recordedMessage: AVAudioFile?

var recordedMessageURL: URL? {
didSet {
if let recordedMessageURL = recordedMessageURL {
recordedMessage = try? AVAudioFile(forReading: recordedMessageURL)
}
}
}

尽管通过CloudKit仪表板访问文件时,我无法播放音频,但该过程似乎可以正常工作。 (双击它会打开iTunes,但不会播放)

我创建了一个fetchPosts函数,该函数成功降低了与记录相关的图像,但是当我尝试播放音频时,出现以下错误:

ExtAudioFile.cpp:192:打开:即将抛出-43:打开音频文件

我认为这与无法正确将 Assets 转换为AVAudioFile有关。它似乎不像转换图像 Assets 那样干净利落。
    var foundAudio: AVAudioFile?
if let audioAsset = ckRecord[PostStrings.audioAssetKey] as? CKAsset {
do {
let audioData = try Data(contentsOf: audioAsset.fileURL!)
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
guard let destinationPath = NSURL(fileURLWithPath: documentsPath).appendingPathComponent("filename.m4a", isDirectory: false) else {return nil}

FileManager.default.createFile(atPath: destinationPath.path, contents: audioData, attributes: nil)

foundAudio = try AVAudioFile(forReading: destinationPath)
} catch {
print("Could not transform asset into data")
}
}

谁能告诉我我要去哪里错了?

最佳答案

花费了很多时间进行更改,但是我得到了一个有效的解决方案,该解决方案不涉及直接将数据作为Data进行操作。相反,我使用URL。我将audioAsset初始化为URL:

var opComment: URL?
var audioAsset: CKAsset? {
get {
guard let audioURL = opComment else { return nil }
return CKAsset(fileURL: audioURL)
}
set {
opComment = newValue?.fileURL
}
}

我使用便利的初始化程序将ckRecord拉回原位:
var opCommentURL: URL?
if let audioAsset = ckRecord[PostStrings.audioAssetKey] as? CKAsset {
opCommentURL = audioAsset.fileURL
}

然后将其作为URL馈入我的AVAudioPlayer中:
        guard let audioURL = post.opComment else {return}

if !isTimerRunning {
do {
audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
audioPlayer.play()
} catch {
print("Error in \(#function) : \(error.localizedDescription) /n---/n \(error)")
}
} else {
audioPlayer.pause()
isTimerRunning = false
}

(如果您正在阅读本文,Sam。感谢您向正确方向的轻柔 push !)

关于swift - 如何在CloudKit中存储音频文件以及如何从中获取音频文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61900119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com