3

我尝试用 Scala 输出一些声音。我的问题是我每秒都会收到短暂的“噪音”/“点击”。类似的java程序没有这个问题。有人知道出了什么问题吗?

斯卡拉 2.9.2 java 1.6.0_31 OS X 10.7.3

import javax.sound.sampled._

object SinSoundMain extends App {
  val SAMPLE_RATE = 44100
  val SAMPLE_SIZE = 16
  val CHANNELS = 1
  val SIGNED = true
  val BIG_ENDIAN = true
  var format = new AudioFormat(SAMPLE_RATE, SAMPLE_SIZE, CHANNELS, SIGNED, BIG_ENDIAN)

  var info = new DataLine.Info(classOf[SourceDataLine], format);

  val auline = (AudioSystem.getLine(info)).asInstanceOf[SourceDataLine]
  auline.open(format)
  auline.start

  val start = System.currentTimeMillis()

  // play 10s
  while(System.currentTimeMillis() < (start + 10000)) {
    var index = 0

    // output blocks of 10000 samples
    var samples = 0.until(10000).map {x =>  math.sin((x+index) * 800.0 / 44100 * math.Pi)}

    // convert samples to Byte Array
    var byteSamples:Array[Byte] = samples.flatMap{ s => 
      val ss = (s * Short.MaxValue).toShort
      List((ss >> 8).toByte, (ss & 0xFF).toByte)
    }.toArray

    auline.write(byteSamples, 0, byteSamples.length)
  }

  // cleanup      
  auline.drain
  auline.close
}
4

1 回答 1

2

您的代码中的错误var index = 0应该是在 while 循环开始之前,并且您应该index += 10000在循环结束时(内部)。这样做,听起来不错。

于 2012-05-16T21:22:35.007 回答