3

I try to output some sound with Scala. My problem is that i get a short "noise"/"click" every second. I didn't had this problem with a similar java program. Has somebody an idea what is wrong?

Scala 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
}
Fabian
  • 1,224
  • 1
  • 11
  • 26

1 Answers1

2

The error in your code is that var index = 0 should be before the start of the while-loop, and you should have index += 10000 at the end of the loop (inside). Do this and it sounds fine.

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180