我正在尝试制作自己的回声垫,实际上直到回声部分都可以
起初我从声音创作开始,它很棒,但是当我开始添加回声效果时,它听起来很愚蠢。
编码
package com.echo;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class WavePlay {
private final static float duration = 1f; // seconds
private final static int sampleRate = 44100;
private final static int numSamples = (int) (duration * sampleRate);
private final static double sample[] = new double[numSamples];
private static SourceDataLine line = null;
private static int freqOfTone = 30;
private static byte[] original;
public static void main(String[] args) {
AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
sampleRate, 8, 1, 1, sampleRate, true);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
}
for (int i = 0; i < numSamples; ++i) {
sample[i] = 255 * Math.sin(2 * Math.PI * i
/ (sampleRate / freqOfTone));
}
final byte generatedSnd[] = new byte[100000];
original = new byte[generatedSnd.length];
for (int i = 0; i < 20000; i++) {
generatedSnd[i] = (byte) (sample[i % sample.length] + 1);
original[i] = generatedSnd[i];
}
// Echo
int delaySamples = 10000;
float decay = 0.3f;
for (int j = 0; j < 5; j++) {
for (int i = 0; i < generatedSnd.length; i++) {
if (i < delaySamples * (j + 1)) {
continue;
}
generatedSnd[i] += (byte) (original[i - delaySamples * (j + 1)] * decay);
}
decay *= 0.4;
}
// play
InputStream source = new ByteArrayInputStream(generatedSnd);
int numRead = 0;
byte[] buf = new byte[line.getBufferSize()];
line.start();
// read and play chunks of the audio
try {
while ((numRead = source.read(buf, 0, buf.length)) >= 0) {
int offset = 0;
while (offset < numRead)
offset += line.write(buf, offset, numRead - offset);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
line.drain();
line.stop();
line.close();
System.exit(0);
}
}
请运行代码并告诉我是否有任何问题
非常感谢提前