简体   繁体   English

如何快速获取mp3文件的图片(重要,因为objectc方法不起作用)

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

I found many oc method said using this code 我发现许多使用此代码的oc方法

*******metadata is a AVMetadataItem class *******元数据是AVMetadataItem类

 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"]];

                  }


               }

      }

I use swift to programming so i try to do that in swift like this 我使用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
}

But when I run , it comes a runtime error: 但是当我运行时,会出现运行时错误:

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

at this line: 在这一行:

let dic = metadata.value as! NSDictionary

who can tell me how to solve the problem THX! 谁能告诉我如何解决THX问题!

If an AVMetadataItem value is in raw data format, it should be accessible with .dataValue . 如果AVMetadataItem值为原始数据格式,则应使用.dataValue访问。

In your case, probably something like this: 就您而言,可能是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM