首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用javax.sound.sampled定期“点击”

使用javax.sound.sampled定期“点击”
EN

Stack Overflow用户
提问于 2012-05-17 04:16:37
回答 1查看 321关注 0票数 3

我试着用Scala输出一些声音。我的问题是,我每秒都会收到一个简短的“噪音”/“点击”。在类似的java程序中,我没有遇到这个问题。有人知道哪里出了问题吗?

Scala 2.9.2 java 1.6.0_31 OS X 10.7.3

代码语言:javascript
复制
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
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-17 05:22:35

代码中的错误是var index = 0应该在while循环的开始之前,并且在循环的末尾(内部)应该有index += 10000。这样做,听起来很好。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10626056

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档