SBT& Scala AudioSystem

时间:2015-07-30 15:03:33

标签: scala sbt specs2

我有一个奇怪的问题,我现在已经想了一会儿。 我有一个应用程序,我正在使用Scala& amp; Spray,它使用AudioSystem API。 我使用SBT构建并测试应用程序。 我有一个boot.scala,它扩展了" App"。 如果我将以下代码放在boot.scala中并通过Eclipse运行(没有sbt)(运行方式... Scala应用程序)它运行良好......

val stream:AudioInputStream = AudioSystem.getAudioInputStream(new File("test.wav"))
val audioFormat:AudioFormat = stream.getFormat();
val samplingRate = audioFormat.getSampleRate()
println("Sampling Rate: "+samplingRate)

按预期输出文件的采样率。 我在Specs2 Route测试中使用相同的代码,类似于......

"API" should {
  "Respond to POST requests" in {
    val stream:AudioInputStream = AudioSystem.getAudioInputStream(new File("test.wav"))
    val audioFormat:AudioFormat = stream.getFormat();
    val samplingRate = audioFormat.getSampleRate()
    println("Sampling Rate: "+samplingRate)
    ...

然而,当我使用" sbt test"从终端执行此操作时我收到以下错误...

UnsupportedAudioFileException: : could not get audio input stream from input file

我知道文件(test.wav)没关系,因为我可以播放它并通过Eclipse执行代码工作正常。终端(及其编码)似乎也没问题,因为我将一个测试文件放在一起,该文件只运行相同的几行代码并成功地从终端运行它。

问题似乎只发生在SBT!

有人有任何想法吗?

由于

1 个答案:

答案 0 :(得分:1)

经过几天的搜索后终于找到了答案......

Why does AudioSystem.getMixerInfo() return different results under sbt vs Scala?

“这是一个类加载器问题.javax.sound不喜欢让上下文类加载器不是系统类加载器。”对我的解决方法是......

val cl = classOf[javax.sound.sampled.AudioSystem].getClassLoader
val old = Thread.currentThread.getContextClassLoader

var audioFormat:AudioFormat = null
try {
  Thread.currentThread.setContextClassLoader(cl)
  val stream:AudioInputStream = 
    AudioSystem.getAudioInputStream(new ByteArrayInputStream(data))
  audioFormat = stream.getFormat()
} finally Thread.currentThread.setContextClassLoader(old)

由于