使用Swift处理ID3标签

13

我正在寻找一种使用Swift修改ID3标签的方法,更具体地说,我想将专辑封面图片写入mp3/m4a文件。

最好是一个Swift库,但我会接受任何可以在Swift中本地完成的内容。我不想依赖于其他语言的库。

我快速查看了AVFoundation,但似乎它只用于音频/视频播放和转换。这是我从ID3标签方面发现的最接近的内容:https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVAsset_Class/

有什么建议吗?


1
这可能对m4a有所帮助:https://dev59.com/2JDea4cB1Zd3GeqPhdzJ - Eric Aya
@EricD。谢谢!我之前没听说过AvMetaData。我会去看一下的。 - LaX
可能是重复问题 https://dev59.com/2JDea4cB1Zd3GeqPhdzJ/ - Richard
@Richard 是的,这是一个非常相似的问题,但是它是在这个问题发布几个月后发布的。 - LaX
1个回答

11
我一次又一次地面临着同样的问题,于是我决定为此制作一个迅速的框架。您可以在这里找到它:https://github.com/philiphardy/ID3Edit 将其添加到您的Xcode项目中,然后确保通过转到项目设置>常规>嵌入式二进制文件来嵌入它。 以下是如何在代码中实现它:
import ID3Edit
...
do
{
   // Open the file
   let mp3File = try MP3File(path: "/Users/Example/Music/example.mp3")
   // Use MP3File(data: data) data being an NSData object
   // to load an MP3 file from memory
   // NOTE: If you use the MP3File(data: NSData?) initializer make
   //       sure to set the path before calling writeTag() or an
   //       exception will be thrown

   // Get song information
   print("Title:\t\(mp3File.getTitle())")
   print("Artist:\t\(mp3File.getArtist())")
   print("Album:\t\(mp3File.getAlbum())")
   print("Lyrics:\n\(mp3File.getLyrics())")

   let artwork = mp3File.getArtwork()

   // Write song information
   mp3File.setTitle("The new song title")
   mp3File.setArtist("The new artist")
   mp3File.setAlbum("The new album")
   mp3File.setLyrics("Yeah Yeah new lyrics")

   if let newArt = NSImage(contentsOfFile: "/Users/Example/Pictures/example.png")
   {
          mp3File.setArtwork(newArt, isPNG: true)
   }
   else
   {
          print("The artwork referenced does not exist.")
   }

   // Save the information to the mp3 file
   mp3File.writeTag() // or mp3.getMP3Data() returns the NSData
                      // of the mp3 file
}
catch ID3EditErrors.FileDoesNotExist
{
   print("The file does not exist.")
}
catch ID3EditErrors.NotAnMP3
{
   print("The file you attempted to open was not an mp3 file.")
}
catch {}

你用了什么来实现这个? - LaX
刚刚使用了Foundation框架。我根据这里的规范手动解析并编写ID3标签:http://id3.org/id3v2-00我已经将我的代码上传到Github。如果你跟随链接,现在应该能够看到它了。 - Philip Hardy
太棒了!谢谢,Philip! - Trevor Alyn
1
这个程序是否也适用于m4a文件?在我的测试中,它无法处理我从iTunes商店购买和下载的音乐文件。 - Marc T.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,