Search code examples
scalamp3mp3agic

How to set and save metadata of mp3 file using mp3agic in Scala


I'm trying to write my own mp3 player. I am able to use mp3agic to read the metadata from an mp3 file, so now I'd like to modify it. Mp3agic shows (under heading Setting ID3v2 field values at mp3agic on GitHub) that you can do it by modifying the tag, then calling save on the mp3 file.

I get an error when I call save. It's the same error as another post Change Album names using mp3agic

Exception in thread "main" com.mpatric.mp3agic.NotSupportedException: Packing Obselete frames is not supported
    at com.mpatric.mp3agic.ID3v2ObseleteFrame.packFrame(ID3v2ObseleteFrame.java:32)
    at com.mpatric.mp3agic.ID3v2Frame.toBytes(ID3v2Frame.java:83)
    at com.mpatric.mp3agic.AbstractID3v2Tag.packSpecifiedFrames(AbstractID3v2Tag.java:275)
    at com.mpatric.mp3agic.AbstractID3v2Tag.packFrames(AbstractID3v2Tag.java:261)
    at com.mpatric.mp3agic.AbstractID3v2Tag.packTag(AbstractID3v2Tag.java:227)
    at com.mpatric.mp3agic.AbstractID3v2Tag.toBytes(AbstractID3v2Tag.java:218)
    at com.mpatric.mp3agic.Mp3File.save(Mp3File.java:450)
    at Example$.$anonfun$new$2(Example.scala:16)

code

import java.nio.file.Paths
import com.mpatric.mp3agic.Mp3File

object Example extends App {
  Paths.get("content").resolve("raw").toFile.listFiles.toList
    .find(f => f.isFile && f.getName.endsWith(".mp3"))
    .foreach { file =>
      val mp3 = new Mp3File(file)
      println(mp3.hasId3v1Tag)
      println(mp3.hasId3v2Tag)
      println(mp3.hasCustomTag)

      val tag = mp3.getId3v2Tag
      println(tag.getYear)
      tag.setComment("Cool song.")
      mp3.save(file.getParentFile.toPath.resolve("x.mp3").toFile.getAbsolutePath)
    }
}

Output

false
true
false
1973

sbt

scalaVersion := "2.13.1"
libraryDependencies += "com.mpatric" % "mp3agic" % "0.9.1"

Solution

  • I was able to set new metadata on an mp3 file, but I had to create a new tag and copy all the data from the old tag over to it, then save the file with the new tag.