argius note

プログラミング関連

♪ハープシコード風?波形

時間と共に振り幅が小さくなる波形を作ってみた。それと、波形をさらに変なかたちに。すると、おもちゃのキーボード(音楽用)のハープシコードのような音になりました。ちゃんと「ぽーん」て鳴った。ちょっとうれしい。
ついでに波形を表示するのをJavaに移植。

import java.awt.*;

import javax.swing.*;

final class GraphScreenCanvas extends JPanel {

    private double sin(double radian) {
        return Math.sin(radian);
    }

    private double cos(double radian) {
        return Math.cos(radian);
    }

    private int exchange(double p) {
        double rate = 100;
        double x = (p + 1) * rate - 10;
        return (int)x;
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        double dec = 1;
        for (double i = -2500; i < 2500; i += 0.1) {
            double n = Math.toRadians(i);
            double x = i / 300f;
            double y;
            // sin(2n) x (cos(3n) x cos(n) ^2
            y = sin(2 * n) * Math.pow(cos(3 * n) * cos(n), 2);
            y *= 20; // basic amp rate
            y /= dec; // dec
            dec *= 1.0001;
            g.fillOval(exchange(x) + 100, exchange(y), 1, 1);
        }
    }

}

public final class GraphScreen extends JFrame {

    public GraphScreen() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().add(new GraphScreenCanvas());
    }

    public static void main(String[] args) {
        GraphScreen gs = new GraphScreen();
        gs.setSize(400, 200);
        gs.setVisible(true);
    }
}