gpt4 book ai didi

audio - 为什么以编程方式生成的和弦听起来不正确?

转载 作者:行者123 更新时间:2023-12-02 22:48:56 26 4
gpt4 key购买 nike

我有以下类,生成包含声音数据的缓冲区:

package musicbox.example;

import javax.sound.sampled.LineUnavailableException;

import musicbox.engine.SoundPlayer;

public class CChordTest {

private static final int SAMPLE_RATE = 1024 * 64;
private static final double PI2 = 2 * Math.PI;

/*
* Note frequencies in Hz.
*/
private static final double C4 = 261.626;
private static final double E4 = 329.628;
private static final double G4 = 391.995;

/**
* Returns buffer containing audio information representing the C chord
* played for the specified duration.
*
* @param duration The duration in milliseconds.
* @return Array of bytes representing the audio information.
*/
private static byte[] generateSoundBuffer(int duration) {

double durationInSeconds = duration / 1000.0;
int samples = (int) durationInSeconds * SAMPLE_RATE;

byte[] out = new byte[samples];

for (int i = 0; i < samples; i++) {
double value = 0.0;
double t = (i * durationInSeconds) / samples;
value += Math.sin(t * C4 * PI2); // C note
value += Math.sin(t * E4 * PI2); // E note
value += Math.sin(t * G4 * PI2); // G note
out[i] = (byte) (value * Byte.MAX_VALUE);
}

return out;
}

public static void main(String... args) throws LineUnavailableException {
SoundPlayer player = new SoundPlayer(SAMPLE_RATE);
player.play(generateSoundBuffer(1000));
}

}

也许我在这里误解了一些物理学或数学知识,但是似乎每个正弦曲线都应该代表每个音符(C,E和G)的声音,并且通过将三个正弦曲线相加,我应该听到类似于我演奏时的声音。键盘上同时显示这三个音符。但是,我所听到的甚至还不止于此。

值得一提的是,如果我注释掉任意两个正弦波并保留第三个正弦波,我确实会听到对应于该正弦波的(正确)音符。

有人可以发现我在做什么错吗?

最佳答案

要合并音频信号,您需要对它们的样本求平均值,而不是对它们求和。

在转换为字节之前,将值除以3。

关于audio - 为什么以编程方式生成的和弦听起来不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37779095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com