add AudioToCAF

This commit is contained in:
uuneo 2025-05-23 11:37:35 +08:00 committed by Feng
parent cea0020f31
commit 30a9f51236

View File

@ -186,10 +186,8 @@ extension SoundsViewController: UIDocumentPickerDelegate {
/// caf
func pickerSoundFile() {
if #available(iOS 14.0, *) {
let types = UTType.types(tag: "caf",
tagClass: UTTagClass.filenameExtension,
conformingTo: nil)
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: types)
/// .audio iOS
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.audio])
documentPicker.delegate = self
documentPicker.allowsMultipleSelection = false
documentPicker.modalPresentationStyle = .pageSheet
@ -208,8 +206,58 @@ extension SoundsViewController: UIDocumentPickerDelegate {
let fileCoordinator = NSFileCoordinator()
let err = NSErrorPointer(nilLiteral: ())
fileCoordinator.coordinate(readingItemAt: url, error: err) { url in
self.importSoundActionRelay.accept(url)
// caf
if url.pathExtension.lowercased() == "caf" {
// caf
self.importSoundActionRelay.accept(url)
} else {
// caf caf
convertAudioToCAF(inputURL: url) { url in
if let url {
//
self.importSoundActionRelay.accept(url)
}
}
}
}
url.stopAccessingSecurityScopedResource()
}
/// CAF
/// - Parameters:
/// - inputURL: URL
/// - completion: CAF URL nil
func convertAudioToCAF(inputURL: URL, completion: @escaping (URL?) -> Void) {
let fileName = inputURL.deletingPathExtension().lastPathComponent
let outputURL = FileManager.default.temporaryDirectory.appendingPathComponent("\(fileName).caf")
do {
if FileManager.default.fileExists(atPath: outputURL.path) {
try FileManager.default.removeItem(at: outputURL)
}
let asset = AVAsset(url: inputURL)
guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough) else {
completion(nil)
return
}
let maxDuration = CMTime(seconds: 29.9, preferredTimescale: 600)
if asset.duration > maxDuration {
exportSession.timeRange = CMTimeRange(start: .zero, duration: maxDuration)
}
exportSession.outputFileType = .caf
exportSession.outputURL = outputURL
exportSession.exportAsynchronously {
DispatchQueue.main.async {
completion(exportSession.status == .completed ? outputURL : nil)
}
}
} catch {
completion(nil)
}
}
}