如何在iOS中的iPod库中获取歌曲的物理文件位置

时间:2013-01-08 12:08:08

标签: iphone ipod mpmediaitem

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

获取该项目的资产网址
[mediaItem valueForProperty: MPMediaItemPropertyAssetURL]

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

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

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

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

1 个答案:

答案 0 :(得分:0)

这会有效,但有点慢。此外,它是为新的MP类编写的:

// song is an instance of MPMediaItem

if let val = song.value(forKey: MPMediaItemPropertyAssetURL) as? URL {
   let asset = AVURLAsset.init(url: val)

   if asset.isExportable {
      let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A)

      let exportPath: NSString = NSTemporaryDirectory().appendingFormat("/\(UUID().uuidString).m4a") as NSString
      let exportUrl: NSURL = NSURL.fileURL(withPath: exportPath as String) as NSURL

      exportSession?.outputURL = exportUrl as URL
      exportSession?.outputFileType = AVFileTypeAppleM4A
      exportSession?.exportAsynchronously(completionHandler: {
          // do some stuff with the file
          do {
            try FileManager.default.removeItem(atPath: exportPath as String!)
          } catch {

       }
}