Java で wave 生成

最近の駒場はアグレッシヴな英語を教えるのですね.
あのリア充どもが自分で実験系なんて組むはずがないではないですか.
なんか音で認知っぽいことをやりたいーとか無邪気にほざくので,
そうか,一般人とっては音を出すというのは難易度が低そうに見えんねんなーとか思いつつ.
ということで,Java で 正弦波を生成してみた.

// freq [Hz]
// duration [msec]
public class SinWave implements LineListener
{
    public final double freq;
    public final int duration;
    public final int rate;
    private final AudioFormat format;
    private byte[] buf;
    private Object monitor;

    public SinWave(double freq, int duration)
    {
        this.freq = freq;
        this.duration = duration;

        rate = 16000;
        format = new AudioFormat((float)rate, 8, 1, true, true);
        monitor = new Object();

        // gen wave
        int duration2 = duration * rate / 1000;
        buf = new byte[duration2];

        double mlt = 2d * Math.PI * freq / rate;
        for (int i = 0; i < duration2; i++) {
            buf[i] = (byte)(127d * Math.sin(mlt * (double)i));
        }
    }
    // 再生.終了まで block
    public void play() throws LineUnavailableException
    {
        Line.Info lineInfo = new Line.Info(Clip.class);
        Clip clip = (Clip)AudioSystem.getLine(lineInfo);
        clip.addLineListener(this);
        clip.open(format, buf, 0, buf.length);
        try {
            clip.start();
            synchronized (monitor) {
                monitor.wait();
            }
        } catch (InterruptedException intre) {
        } finally {
            clip.close();
        }
    }
    // implement LineListener.update
    public void update(LineEvent e)
    {
        if (e.getType() == LineEvent.Type.STOP) {
            synchronized (monitor) {
                monitor.notify();
            }
        }
    }
    // ついでに wave ファイルに保存
    public void save(File dest) throws IOException
    {
        InputStream in = new ByteArrayInputStream(buf);
        AudioInputStream ais = new AudioInputStream(in, format, buf.length);
        AudioSystem.write(ais, AudioFileFormat.Type.WAVE, dest);
    }
}

感想.Java はやっぱりやればできる子.


まあ,Java Applet とかを考えたらこういうのがあるのは当たり前なのですが.
しかし,最初は Win32 か? ALSA か? それともまさか…と戦々恐々だったので,
これだけで済んでなにより.