Skip to content

Instantly share code, notes, and snippets.

@pdalpra
Created May 11, 2014 20:20
Show Gist options
  • Save pdalpra/834161fe6d09b20b931d to your computer and use it in GitHub Desktop.
Save pdalpra/834161fe6d09b20b931d to your computer and use it in GitHub Desktop.
Wav -> Flac Converter
import java.io.File
import java.util.concurrent.{ Callable, ForkJoinPool }
import scala.annotation.tailrec
import scala.collection.JavaConverters._
import scala.sys.process.Process
import scala.util.Try
val source = Try(args(0)).toOption
val dest = Try(args(1)).toOption
source match {
case Some(dir) =>
val dirAsFile = new File(dir)
if(dirAsFile.isDirectory) {
val allFiles = listAllWavFiles(dirAsFile)
val allTracks = allFiles.map(toTrack)
val args = allTracks.map(makeArgs)
val destFolders = allTracks.map(_.path.getParentFile.toString.replaceAll(source.get, dest.get))
destFolders.foreach(path => new File(path).mkdirs)
val fjp = new ForkJoinPool()
fjp.invokeAll(args.map(args =>prepareTask(args)).asJava)
} else {
println("The specified path is not a directory.")
}
case None =>
println("You must specify a directory.")
sys.exit()
}
def listAllWavFiles(root: File): List[File] = {
@tailrec
def aux(root: File, allFiles: List[File], remainingFolders: List[File]): List[File] = {
val children = root.listFiles.toList
val (folders, files) = children.partition(_.isDirectory)
val newAllFiles = files.filter(_.getName.endsWith(".wav")) ++ allFiles
val newRemaining = remainingFolders ++ folders
newRemaining match {
case Nil => allFiles
case x :: s => aux(x, newAllFiles, s)
}
}
aux(root, Nil, Nil)
}
def toTrack(file : File): Track = {
val album = file.getParentFile.getName
val artist = file.getParentFile.getParentFile.getName
val trackAndTitle = file.getName.split(" ")
Track(file, artist, album, trackAndTitle.tail.mkString(" ").replaceAll(".wav", ""), trackAndTitle.head.toInt)
}
case class Track(path: File, artist: String, album: String, title: String, trackNumber: Int)
def tag(tagName: String, tagValue: String) = Seq("-T", s"""$tagName=$tagValue""")
def makeArgs(track: Track): Seq[String] = Seq("--best", "-o", track.path.toString.replaceAll(source.get, dest.get).replaceAll(".wav", ".flac")) ++ Seq(
tag("TITLE", track.title),
tag("ALBUM", track.album),
tag("ARTIST", track.artist),
tag("TRACKNUMBER", track.trackNumber.toString)
).flatten ++ Seq(track.path.toString)
def prepareTask(args: Seq[String]) = new Callable[Int] {
override def call() = Process("flac", args).!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment