问题描述
我想产生幅度和频率可以动态变化的正弦波。我不能为此使用预先存在的音频文件。 documentation for the package media
说:
在某些情况下,容器格式可能只是包含编码数据的基本流。
我打算使用代表幅度(脉冲代码调制)的值流播放音频。 这是我的目标的伪代码:
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
}
我的问题是类 Media
的唯一构造函数采用 URI 参数。 AudioClip
也是如此。我希望他们将 Stream
作为参数。
任何建议或建议都会有所帮助。
解决方法
据我所知,目前没有一种方法可以使用 JavaFX 做您想做的事。
我建议您使用 javax.sound.sampled.SourceDataLine
作为您的输出行。我已经将这个类用于类似特雷门的实时程序、实时 FM 合成器以及名为 AudioCue 的开源增强版 Clip
。
基本计划如下:
- 使用给定的
SourceDataLine
打开输出行 (AudioFormat
) - 生成表示所需波形(一个缓冲区的值)的 PCM 值(例如,范围从 -1 到 1 的浮点数)
- 根据
AudioFormat
的要求将 PCM 转换为字节 - 使用
SourceDataLine
方法编写 write - 在声音的持续时间内循环回到 (2)