我正在尝试生成正弦波并将其添加到字节数组。我搜索并找到了。但是,我总是像附件一样得到失真的波形。
请告诉我您的意见,为什么会这样。谢谢。
我的代码在这里
private byte[] getData(int freq) { // taking pitch data
double pha = Math.PI/2; // defining phase
final int LENGTH = 44100 * 10; // defining length of sine wave, byte array
final byte[] arr = new byte[LENGTH];
for(int i = 0; i < arr.length; i++) {
double angle = (2.0 * Math.PI * i*freq+pha) / (44100);
arr[i] = (byte) (Math.cos(angle) *127* 0.3); // 0.3 is amplitude scale
}
return arr;
}
最佳答案
代码看起来不错。我怀疑这是解释 two's complement 的可视化工具有符号值作为无符号(-1
变为 255
,-2
变为 254
等等)。
I write to a wav file and plot it with SonicVisualiser
根据 WAVE PCM soundfile format :
8-bit samples are stored as unsigned bytes, ranging from 0 to 255. 16-bit samples are stored as 2's-complement signed integers, ranging from -32768 to 32767.
看起来您要么需要将正弦波向上移动 128(以便它完全适合 0-255 范围内),要么转向使用 16 位样本。
关于java - 正弦波在Java中交替失真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26632480/