func export(_ assetURL: URL, completionHandler: @escaping (_ fileURL: URL?, _ error: Error?) -> ()) { let asset = AVURLAsset(url: assetURL) guard let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else { completionHandler(nil, ExportError.unableToCreateExporter) return } let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent(NSUUID().uuidString) .appendingPathExtension("m4a") exporter.outputURL = fileURL exporter.outputFileType = "com.apple.m4a-audio" exporter.exportAsynchronously { if exporter.status == .completed { completionHandler(fileURL, nil) } else { completionHandler(nil, exporter.error) } } } func exampleUsage(with mediaItem: MPMediaItem, completionHandler : @escaping (_ songData:NSData?) -> ()) { if let assetURL = mediaItem.assetURL { export(assetURL) { fileURL, error in guard let fileURL = fileURL, error == nil else { print("export failed: \(error)") completionHandler(nil) return } // use fileURL of temporary file here print("Exported File : \(fileURL)") if let rawData = NSData(contentsOf: fileURL) { print("Exported File length : ",rawData.length) completionHandler(rawData) } } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)