Last active
August 29, 2015 14:25
-
-
Save Sciss/5d42f55e068c8307a30b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import scala.concurrent.{blocking, Future, ExecutionContext} | |
| def trim(path: String): Future[Unit] = { | |
| import ExecutionContext.Implicits.global | |
| val in = file(path) | |
| val out = in.parent / s"${in.base}-trim.${in.ext}" | |
| val res = if (out.exists) { | |
| Future.failed(new Exception(s"Output file $out already exists. Not overwriting!")) | |
| } else Future { | |
| blocking { | |
| import de.sciss.synth.io.AudioFile | |
| val afIn = AudioFile.openRead(in) | |
| try { | |
| val buf = afIn.buffer(8192) | |
| var startFrame = Long.MaxValue | |
| var stopFrame = 0L | |
| var read = 0L | |
| var num = afIn.numFrames | |
| while (read < num) { | |
| val chunk = math.min(8192, num - read).toInt | |
| afIn.read(buf, 0, chunk) | |
| buf.foreach { ch => | |
| for (i <- 0 until chunk) { | |
| val f = ch(i) | |
| if (f != 0f) { | |
| val j = read + i | |
| startFrame = math.min(startFrame, j) | |
| stopFrame = math.max(stopFrame , j + 1) | |
| } | |
| } | |
| } | |
| read += chunk | |
| } | |
| startFrame = math.min(startFrame, stopFrame) | |
| println(s"Found $startFrame samples of silence at beginning and ${num - stopFrame} at end of file") | |
| afIn.seek(startFrame) | |
| val afOut = AudioFile.openWrite(out, afIn.spec.copy(numFrames = 0)) | |
| try { | |
| afIn.copyTo(afOut, stopFrame - startFrame) | |
| } finally { | |
| afOut.close() | |
| } | |
| } finally { | |
| afIn.close() | |
| } | |
| println("Done.") | |
| } | |
| } | |
| res.onFailure { | |
| case ex => println(s"Failed: ${ex.getMessage}") | |
| } | |
| res | |
| } | |
| // trim("/home/hhrutz/Documents/temp/murke_test.aif") | |
| // trim("/home/hhrutz/Documents/temp/murke_test-trim.aif") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment