获取音频中信息(根据音乐路径获取歌手,专辑,歌名,图片)

oc

-(NSDictionary *)getMuiscInfoFromMuiscFile:(NSString *)filePath{
    NSDictionary *dict = [NSDictionary dictionary];
    NSURL  *fileURL = [NSURL  fileURLWithPath:filePath];
    AVURLAsset *avURLAsset = [[AVURLAsset alloc] initWithURL:fileURL options:nil];
    for (NSString *string  in [avURLAsset availableMetadataFormats]){

        for (AVMetadataItem *metadata in [avURLAsset metadataForFormat:string]){
            if([metadata.commonKey isEqualToString:@"title"]){
                NSString *title = (NSString *)metadata.value;//提取歌曲名
                [dict setValue:title forKey:@"title"];
                NSLog(@"歌名 = %@",title);

            }
            if([metadata.commonKey isEqualToString:@"albumName"]){
                NSString *albumName = (NSString *)metadata.value;//提取歌曲名
                [dict setValue:albumName forKey:@"albumName"];
                NSLog(@"专辑 = %@",albumName);

            }
            if([metadata.commonKey isEqualToString:@"artist"]){
                NSString *artist = (NSString *)metadata.value;//提取歌曲名
                [dict setValue:artist forKey:@"artist"];
                NSLog(@"歌手 = %@",artist);

            }
            if([metadata.commonKey isEqualToString:@"artwork"]){
                UIImage *image = [UIImage imageWithData:(NSData *)metadata.value];//提取图片
                [dict setValue:image forKey:@"image"];

            }
        }
    }
    return dict;
}

SWIFT

struct MusicInfo {
    var musicName = String() //歌名
    var albumName = String() //专辑
    var artist = String()    //歌手
    var image = UIImage()
}

func getMusicInfoFromMusicFile(filePath:String)-> MusicInfo{
        let url = URL(fileURLWithPath: filePath)
        let asset = AVURLAsset(url: url)
        var musicInfo = MusicInfo()
        for format:AVMetadataFormat in asset.availableMetadataFormats {
            for metadata:AVMetadataItem in asset.metadata(forFormat: format){
                let key = metadata.commonKey?.rawValue
                if key == "title"{ //歌名
                    musicInfo.musicName = metadata.value as! String
                }else if key == "albumName"{ //专辑
                    musicInfo.albumName = metadata.value as! String
                }else if key == "artist"{   //歌手
                    musicInfo.artist = (metadata.value as! String)
                }else if key == "artwork"{  //图片
                    musicInfo.image = UIImage(data: metadata.value as! Data)!
                }

            }
        }
        return musicInfo
    }

你可能感兴趣的:(获取音频中信息(根据音乐路径获取歌手,专辑,歌名,图片))