package lt.bit.laikas; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.swing.*; import java.awt.*; public class Vykdymas { public static float SAMPLE_RATE = 8000f; public static void tone(int hz, int msecs, double vol) throws LineUnavailableException { byte[] buf = new byte[1]; AudioFormat af = new AudioFormat( SAMPLE_RATE, // sampleRate 8, // sampleSizeInBits 1, // channels true, // signed false); // bigEndian SourceDataLine sdl = AudioSystem.getSourceDataLine(af); sdl.open(af); sdl.start(); for (int i=0; i < msecs*8; i++) { double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI; buf[0] = (byte)(Math.sin(angle) * 127.0 * vol); sdl.write(buf,0,1); } sdl.drain(); sdl.stop(); sdl.close(); } public static void main(String[] args) { JFrame f=new JFrame("Chronometras"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(600,400); f.setLocationRelativeTo(null); JPanel p=new JPanel(); JButton start=new JButton("Start"); JButton pause=new JButton("Pause/Resume"); JButton reset=new JButton("Reset"); JLabel out=new JLabel("0.0", SwingConstants.CENTER); out.setFont(new Font("Serif", Font.BOLD, 64)); Laikas l=new Laikas(out); l.start(); start.addActionListener((e)->{ l.setRunning(true); try { tone(300,2000,0.5); } catch (LineUnavailableException ex) { ex.printStackTrace(); } }); pause.addActionListener((e)->{ l.setRunning( ! l.isRunning() ); }); reset.addActionListener((e)->{ l.reset(); }); p.add(start); p.add(pause); p.add(reset); f.add(out, BorderLayout.CENTER); f.add(p, BorderLayout.PAGE_END); f.setVisible(true); } }