您将需要一个用于计算声波值的 PCM 值数组,以及一个用于保存要写入SourceDataLine 的值的字节数组。
PCM 数组的大小设置为您正在创建的波形的周期。因此,如果您想制作 A 440,则周期(基于 44100fps 的采样率)将是 100(440 有点尖锐)。
第一步是用随机数填充 PCM 数组(浮点数就足够了,范围在 -1 到 1 之间)。
然后循环执行以下两步(从第二步开始):
- 根据您引用的公式计算下一组 PCM 值。
- 根据您的音频格式将 PCM 缓冲区值转换为字节,并将其附加到将写入
SourceDataLine 的字节数组中。
当SourceDataLine 的字节缓冲区已满时,写入缓冲区并开始重新填充它以进行下一次写入操作。
有一个article here 也描述了算法的一些改进。将 PCM 转换为每个音频格式的字节的详细信息已在其他帖子中介绍。
以下是一个快速而肮脏的实现。该代码仅播放 200-pcm 音符。显然,人们想要重写它以使其适用于其他笔记。但它确实显示了算法的实际作用,并且确实发挥了作用。
public class KarplusStrongTone {
float[] pcmArray;
SourceDataLine sdl;
int period = 200;
int sdlIdx = 0;
byte sdlBuffer[] = new byte[4000];
public static void main(String[] args) throws UnsupportedAudioFileException,
IOException, InterruptedException, LineUnavailableException {
KarplusStrongTone kst = new KarplusStrongTone();
kst.initializePCMArray();
kst.makeOutputLine();
kst.play();
}
private void initializePCMArray()
{
pcmArray = new float[period];
for (int i = 0; i < period; i++) pcmArray[i] = (float)(Math.random() * 2 - 1);
}
private void makeOutputLine() throws LineUnavailableException {
AudioFormat audioFmt = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
44100, 16, 1, 2, 44100, false);
Info info = new DataLine.Info(SourceDataLine.class, audioFmt);
sdl = (SourceDataLine)AudioSystem.getLine(info);
sdl.open();
sdl.start();
}
private void play()
{
int countIterations = 0;
float localMax = 1;
while (localMax > 0.00001f)
{
localMax = 0;
for (int i = period - 1; i > 0; i--)
{
pcmArray[i] = (pcmArray[i] + pcmArray[i-1])/2;
localMax = Math.max(Math.abs(pcmArray[i]), localMax);
}
pcmArray[0] = pcmArray[0]/2;
countIterations++; // just curious how long while runs
ship(pcmArray);
}
System.out.println("Iterations = " + countIterations);
}
private void ship(float[] pcm)
{
for (int i = 0; i < period; i++)
{
int audioVal = (int)(pcm[i] * 32767);
sdlBuffer[sdlIdx + i * 2] = (byte)audioVal;
sdlBuffer[sdlIdx + (i * 2) + 1] = (byte)(audioVal >> 8);
}
sdlIdx += (period * 2);
if (sdlIdx == 4000)
{
sdl.write(sdlBuffer, 0, 4000);
sdlIdx = 0;
}
}
}