如何在 swift 中获取 mp3 文件的插图(很重要,因为对象方法不起作用)

how to get mp3 file's artwork in swift(important because the objectc method doesn't work)

我发现很多 oc 方法都说使用这个代码

*****元数据是一个 AVMetadataItem class

 NSString *path =[ [NSBundle mainBundle]  pathForResource:@"musicname" ofType:@"mp3"];

     NSURL  *fileURL = [NSURL  fileURLWithPath:path];

      AVURLAsset *avURLAsset = [[AVURLAsset alloc] initWithURL:fileURL options:nil];

      for (NSSting *format  in [avURLAsset availableMetadataFormats]){

              for (AVMetadataItem *metadata in [avURLAsset metadataForFormat:format]){

                  if([metadata.commonKey isEqualToString:@"title"]){

                        NSSting *title = (NSSting *)metadata.value;

                   }

                  if([metadata.commonKey isEqualToString:@"artwork"]){

                       UIImage *coverImage = [UIImage imageWithData:[(NSDictionary *)metadata.value objectForKey:@"data"]];

                  }


               }

      }

我使用 swift 编程,所以我尝试在 swift 中像这样

func getArtworkForTrack(trackNumber: Int) -> NSData {
    let asset = trackAVURLAssets[trackNumber]
    var artworkData: NSData = NSData()
    for metadata in asset.metadata {
        if let commonKey = metadata.commonKey {
            if commonKey == "artwork" {
                if let keySpace = metadata.keySpace {
                    if keySpace == AVMetadataKeySpaceiTunes {
                        print("keyspace == AVMetadataKeySpaceiTunes")
                        artworkData = (metadata.value?.copyWithZone(nil))! as! NSData
                    } else {
                        let dic = metadata.value as! NSDictionary
                        let image = UIImage(data: dic.objectForKey("data") as! NSData)
                    }
                }
            }
        }
    }

    return artworkData
}

但是当我 运行 时,出现 运行时间错误:

Could not cast value of type '__NSCFData' (0xbdbe94) to 'NSDictionary' (0xbdc394).
(lldb) 

在这一行:

let dic = metadata.value as! NSDictionary

谁能告诉我怎么解决这个问题,谢谢!

如果 AVMetadataItem 值是原始数据格式,它应该可以通过 .dataValue 访问。

在你的情况下,可能是这样的:

if let data = metadata.dataValue {
    let image = UIImage(data: data)
}