Swift如何在macOS中编辑.mp3文件的元数据(ID3)
我正在编写一个macOS应用程序并且已经尝试了一段时间来改变.mp3中“更多信息”部分的措辞,并且已经做了很多SO搜索并找到了2个代码片段,它们将读取元数据但是只有一个实际输出现有的密钥,但我不明白如何将新数据写入其中任何一个。我实际上想要将数据写入我创建的.mp3文件并尽可能添加图像,因为有一些Swift 3知识的新手可以帮助任何人。下面的输出来自我复制到桌面的测试歌曲(Imagine_Test_Song)。
我在SO Writing ID3 tags via AVMetaDataItem上找到了这个,但我在这些行中得到了编译错误: -
soundFileMetadata.append(createMetadata(AVMetadataiTunesMetadataKeyArtist, "MyArtist")!) // compiler error here
soundFileMetadata.append(createMetadata(AVMetadataiTunesMetadataKeySongName, "MySong")!)
….
其中说: - 缺少参数标签' tagKey'在电话中。功能如下: -
func createMetadata(tagKey: String, _ tagValue: AnyObject?,
keySpace:String = AVMetadataKeySpaceiTunes) -> AVMutableMetadataItem? {
if let tagValue = tagValue {
let tag = AVMutableMetadataItem()
tag.keySpace = keySpace
tag.key = tagKey as NSCopying & NSObjectProtocol
tag.value = (tagValue as? String as! NSCopying & NSObjectProtocol) ?? (tagValue as? Int as! NSCopying & NSObjectProtocol)
return tag
}
return nil
}
第二个片段是我下面的代码,它编译并输出各种数据,但是如何编辑文本并保存更改。理想情况下,我也想添加“艺术品”,这可能吗?
let homeUrl = NSHomeDirectory()
let sourceFilePath = String(format: "%@/Desktop/%@.mp3", homeUrl, " Imagine_Test_Song")
let fileUrl = NSURL(fileURLWithPath: sourceFilePath)
var asset = AVAsset(url: fileUrl as URL) as AVAsset
//using the asset property to get the metadata of file
for metaDataItems in asset.commonMetadata {
//getting the title of the song
if metaDataItems.commonKey == "title" {
let titleData = metaDataItems.value as! NSString
print("title = \(titleData)")
}
//getting the "Artist of the mp3 file"
if metaDataItems.commonKey == "artist" {
let artistData = metaDataItems.value as! NSString
print("artist = \(artistData)")
}
//getting the "creator of the mp3 file"
if metaDataItems.commonKey == "creator" {
let creatorData = metaDataItems.value as! NSString
print("creator = \(creatorData)")
}
//getting the "Album of the mp3 file"
if metaDataItems.commonKey == "albumName" {
let albumNameData = metaDataItems.value as! NSString
print("albumName = \(albumNameData)")
}
输出: -
title = Imagine
creator = John Lennon
type = Singer-Songwriter
albumName = Imagine
任何帮助将不胜感激,提前谢谢。