有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用正弦波进行流畅的转换

我有以下代码:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class Test {
    private static final int MAX_LENGTH = 1000;
    private Random r = new Random();
    protected static final int SAMPLE_RATE = 32 * 1024;

    public static byte[] createSinWaveBuffer(double freq, int ms) {
        int samples = ((ms * SAMPLE_RATE) / 1000);
        byte[] output = new byte[samples];
        double period = (double) SAMPLE_RATE / freq;
        for (int i = 0; i < output.length; i++) {
            double angle = 2.0 * Math.PI * i / period;
            output[i] = (byte) (Math.sin(angle) * 0x7f);
        }
        return output;
    }

    public static void main(String[] args) throws LineUnavailableException {
        List<Double> freqs = new Test().generate();
        System.out.println(freqs);
        final AudioFormat af = new AudioFormat(SAMPLE_RATE, 8, 1, true, true);
        SourceDataLine line = AudioSystem.getSourceDataLine(af);
        line.open(af, SAMPLE_RATE);
        line.start();
        freqs.forEach(a -> {
            byte[] toneBuffer = createSinWaveBuffer(a, 75);
            line.write(toneBuffer, 0, toneBuffer.length);
        });
        line.drain();
        line.close();
    }

    private List<Double> generate() {
        List<Double> frequencies = new ArrayList<>();
        double[] values = new double[] { 4.0/3,1.5,1,2 };
        double current = 440.00;
        frequencies.add(current);
        while (frequencies.size() < MAX_LENGTH) {
            //Generate a frequency in Hz based on harmonics and a bit math.
            boolean goUp = Math.random() > 0.5;
            if (current < 300)
                goUp = true;
            else if (current > 1000)
                goUp = false;
            if (goUp) {
                current *= values[Math.abs(r.nextInt(values.length))];
            } else {
                current *= Math.pow(values[Math.abs(r.nextInt(values.length))], -1);
            }
            frequencies.add(current);
        }
        return frequencies;
    }

}

我想生成一个随机的“旋律”,从a开始(hz=440)。我使用随机数来确定音调是上升还是下降

我的问题是: 我可以产生旋律,但如果我演奏它,每个音调之间总是有一个“敲击”的声音。我该怎么做才能去掉它,这样听起来更好


共 (0) 个答案