参考 Krishna 的答案,使用 AVAssetExportSession
将 MPMediaItem
保存到文件中。在 Swift 3 中,您可以像以下这样做:
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) {
if let assetURL = mediaItem.assetURL {
export(assetURL) { fileURL, error in
guard let fileURL = fileURL, error == nil else {
print("export failed: \(error)")
return
}
print("\(fileURL)")
}
}
}
enum ExportError: Error {
case unableToCreateExporter
}
或者,在 Swift 2 中:
func export(assetURL: NSURL, completionHandler: (NSURL?, ErrorType?) -> ()) {
let asset = AVURLAsset(URL: assetURL)
guard let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else {
completionHandler(nil, ExportError.unableToCreateExporter)
return
}
let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory())
.URLByAppendingPathComponent(NSUUID().UUIDString)!
.URLByAppendingPathExtension("m4a")
exporter.outputURL = fileURL
exporter.outputFileType = "com.apple.m4a-audio"
exporter.exportAsynchronouslyWithCompletionHandler {
if exporter.status == .Completed {
completionHandler(fileURL, nil)
} else {
completionHandler(nil, exporter.error)
}
}
}
func exampleUsage(with mediaItem: MPMediaItem) {
if let assetURL = mediaItem.assetURL {
export(assetURL) { fileURL, error in
guard let fileURL = fileURL where error == nil else {
print("export failed: \(error)")
return
}
print("\(fileURL)")
}
}
}
enum ExportError: ErrorType {
case unableToCreateExporter
}
你可以看到,我将它放在了一个临时文件夹而不是文档文件夹中。此外,我使用 UUID 而不是自某个参考日期以来的秒数来生成临时文件。但基本思想是相同的。
NSData
/Data
对象中(因为它们同时保存在内存中),而是通常流式传输音乐文件。 - Rob