我尝试用 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
}