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

标签 audio physics midi trigonometry

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

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/

相关文章:

audio - 按下按钮后,如何在Codename One中预定义的时间后自动开始视频录制并自动停止?

html - IE 11无法在音频标签中播放OGG文件

java - 矩形之间的碰撞

python - 分离轴定理和Python

ios - 有没有办法在 iOS 4.2 之前的设备上使用 Core MIDI?

android - 是否可以更改内置在Midi Player弯音范围内的android?

c - 将 Midi 序列写入文件

amazon-web-services - 通过 MediaLive 服务器进行音频流式传输

android - 如何在 Android 中读取音频文件的时间样本?

canvas - 弹跳速度计算、与地面碰撞