在 JavaFx 中动态产生声音

Dynamically producing sound in JavaFx

我想生成一个振幅和频率可以动态变化的正弦波。我不能为此使用预先存在的音频文件。 documentation for the package media 表示:

In some cases the container format might simply be an elementary stream containing the encoded data.

我打算使用表示振幅(脉冲编码调制)的值流来播放音频。 这是我的目标的伪代码:

double frequency;
double interval; //interval between successive additions to the audio stream
double time = 0;
streamObject; //some stream object which contains amplitudes as integers in range [-128,128]

while (true){
    double value = Math.sin(time*2*Math.PI*frequency);
    streamObject.write( (int)(value*128) ); //this is some method which will append values to the end of the stream
    time += interval;
    wait(interval); //appending values in real-time because there may be changes to the frequency
}

我的问题是 class Media takes a URI parameter. It is the same for AudioClip 的唯一构造函数。我希望他们将 Stream 作为参数。

任何意见或建议都会有所帮助。

据我所知,目前没有办法用 JavaFX 做你想做的事。

我建议使用 javax.sound.sampled.SourceDataLine 作为输出行。我已经将此 class 用于类似 theremin 的实时程序、实时 FM 合成器和名为 AudioCueClip 的开源增强版本。

基本计划如下:

  1. 用给定的 AudioFormat
  2. 打开一个输出行 (SourceDataLine)
  3. 生成表示所需波形(一个缓冲区的价值)的 PCM 值(例如,范围从 -1 到 1 的浮点数)
  4. 根据 AudioFormat
  5. 的要求将 PCM 转换为字节
  6. 使用SourceDataLine方法写入write
  7. 在声音的持续时间内循环回到 (2)