ios - 是否可以使用 swift 将 Ipod 库中的音乐保存到我的应用程序中?

标签 ios swift audio-player ituneslibrary

当用户从 iPod 库中选择音频时,我有 MPMediaItem 的引用。我正在使用

获取该项目的 Assets URL
 let url = item.valueForProperty(MPMediaItemPropertyAssetURL)

但这并没有给我文件的确切物理位置,而是给了我一个 URL w.r.t iPod 库。

ipod-library://item/item.mp3?id=1840064795502796074

有没有办法从 iPod 库中获取歌曲的物理 URL?

编辑 - 实际上我想从物理文件中提取 NSData 并将其发送到我的后端服务器,所以我需要物理文件 URL 而不是相对 URL

MPmediaPickerController 正在工作,我选择了歌曲并播放但我不想播放这首歌。我已尝试将音频文件上传到服务器。我在列表音频中使用 MPMedia Picker View ,当我要选择要上传到服务器 (HTTP) 的音频时,我该怎么做???如何使用Swift代码访问媒体库?

最佳答案

改编 Krishna 的答案,它使用 AVAssetExportSessionMPMediaItem 保存到文件中,您可以在 Swift 3 中执行类似以下操作:

/// Export MPMediaItem to temporary file.
///
/// - Parameters:
///   - assetURL: The `assetURL` of the `MPMediaItem`.
///   - completionHandler: Closure to be called when the export is done. The parameters are a boolean `success`, the `URL` of the temporary file, and an optional `Error` if there was any problem. The parameters of the closure are:
///
///   - fileURL: The `URL` of the temporary file created for the exported results.
///   - error: The `Error`, if any, of the asynchronous export process.

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
            }

            // use fileURL of temporary file here
            print("\(fileURL)")
        }
    }
}

enum ExportError: Error {
    case unableToCreateExporter
}

或者,在 Swift 2 中:

/// Export MPMediaItem to temporary file.
///
/// - Parameters:
///   - assetURL: The `assetURL` of the `MPMediaItem`.
///   - completionHandler: Closure to be called when the export is done. The parameters are a boolean `success`, the `URL` of the temporary file, and an optional `Error` if there was any problem. The parameters of the closure are:
///
///   - fileURL: The `URL` of the temporary file created for the exported results.
///   - error: The `Error`, if any, of the asynchronous export process.

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
            }

            // use fileURL of temporary file here
            print("\(fileURL)")
        }
    }
}

enum ExportError: ErrorType {
    case unableToCreateExporter
}

如您所见,我将其放在一个临时文件夹中,而不是 Documents 文件夹中。此外,我使用 UUID 而不是自某个引用日期以来的秒数来生成临时文件。但思路基本相同。

关于ios - 是否可以使用 swift 将 Ipod 库中的音乐保存到我的应用程序中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40924922/

相关文章:

ios - 如何从另一个 View Controller 访问按钮?

javascript - 元素 : Tracking a bouncing ball across a music score

android - 在Android中清除AudioRecord缓冲区

ios - 在另一个 View Controller 中时的消息通知

ios - 在prepareForSegue之后文本未完全通过(swift 3)

iOS 应用程序 : Possible to make keyboard recommendations?

iOS map 套件 : Show white dots on polyline route

iOS蓝牙设备在输入错误密码后无法取消配对或忘记

ios - 如何从 Viewcontroller 转到 UITableViewCell

javascript - 将 onKeyDown 事件与 CharCode 结合使用