package ru.tone;

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

/**
 * User: dima
 * Date: 03/10/2012
 */
public class Tone {

    public static void main(String[] args) throws LineUnavailableException {
        final AudioFormat af =
                new AudioFormat(Note.SAMPLE_RATE, 8, 1, true, true);
        SourceDataLine line = AudioSystem.getSourceDataLine(af);
        line.open(af, Note.SAMPLE_RATE);
        line.start();

        play(line, Note.A4, 500);
//        play(line, Note.REST, 10);

/*
        for  (Note n : Note.values()) {
            play(line, n, 500);
            play(line, Note.REST, 10);
        }
*/
        line.drain();
        line.close();
    }

    private static void play(SourceDataLine line, Note note, int ms) {
        ms = Math.min(ms, Note.SECONDS * 1000);
        int length = Note.SAMPLE_RATE * ms / 1000;
        int count = line.write(note.data(), 0, length);
    }
}

enum Note {
    REST, A4, A4$, B4, C4, C4$, D4, D4$, E4, F4, F4$, G4, G4$, A5;
    public static final int SAMPLE_RATE = 16 * 1024; // ~16KHz
    public static final int SECONDS = 2;
    private byte[] sin = new byte[SECONDS * SAMPLE_RATE];

    Note() {
        int n = this.ordinal();
        if (n > 0) {
            double exp = ((double) n - 1) / 12d;
            double f = 440d * Math.pow(2d, exp);
            for (int i = 0; i < sin.length; i++) {
                double period = (double)SAMPLE_RATE / f;
                double angle = 2.0 * Math.PI * i / period;
                sin[i] = (byte)(Math.sin(angle) * 127f);
            }
        }
    }

    public byte[] data() {
        return sin;
    }
}

@@ -585,16 +585,61 @@
 ote.A4, 
+2500);%0A//        play(line, new NoteFreq(), 2
 500);%0A//
@@ -906,16 +906,24 @@
 ne, 
-Note not
+Playable playabl
 e, i
@@ -1065,11 +1065,15 @@
 ite(
-not
+playabl
 e.da
@@ -1103,16 +1103,568 @@
 %0A%7D%0A%0A
-enum Not
+class NoteFreq implements Playable %7B%0A    private final byte%5B%5D sin;%0A%0A    NoteFreq(int frequency) %7B%0A        sin = new byte%5BNote.SECONDS * frequency%5D;%0A%0A        for (int i = 0; i %3C sin.length; i++) %7B%0A            double f = 440d * Math.pow(2d, 1 - 1);%0A            double period = (double)frequency / f;%0A            double angle = 2.0 * Math.PI * i / period;%0A            sin%5Bi%5D = (byte)(Math.sin(angle) * 127f);%0A        %7D%0A    %7D%0A%0A    @Override public byte%5B%5D data() %7B%0A        return sin;%0A    %7D%0A%7D%0A%0Ainterface Playable %7B%0A    byte%5B%5D data();%0A%7D%0A%0Aenum Note implements Playabl
 e %7B%0A
@@ -2308,24 +2308,38 @@
    %7D%0A    %7D%0A%0A
+    @Override%0A
     public b

tones . 1