fork download
  1.  
  2.  
  3. import java.util.Arrays;
  4.  
  5. import javax.sound.sampled.AudioFormat;
  6. import javax.sound.sampled.AudioSystem;
  7. import javax.sound.sampled.LineUnavailableException;
  8. import javax.sound.sampled.SourceDataLine;
  9.  
  10.  
  11. public class Main {
  12.  
  13.  
  14. public static void main(String[] args) throws LineUnavailableException {
  15.  
  16. Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
  17.  
  18. // サンプリングレート: 44100 Hz
  19. int sampleRate = 44100;
  20.  
  21. // ラ(A3): 220 Hz
  22. int frequency = 220;
  23.  
  24. int l = sampleRate / frequency;
  25. int c = l / 2;
  26. int v = 0x07;
  27.  
  28. // 1波長分の矩形波データ
  29. byte[] b = new byte[l];
  30. Arrays.fill(b, 0, c, (byte) +v);
  31. Arrays.fill(b, c, l, (byte) -v);
  32.  
  33. // PCM_SIGNED 44100.0 Hz, 8 bit, mono, 1 bytes/frame
  34. AudioFormat f = new AudioFormat(sampleRate, 8, 1, true, true);
  35.  
  36. try(SourceDataLine line = AudioSystem.getSourceDataLine(f)) {
  37.  
  38. long startTime = System.currentTimeMillis();
  39.  
  40. // 10ミリ秒分のバッファを用意する
  41. line.open(f, sampleRate * 10 / 1000);
  42. line.start();
  43.  
  44. while (true) {
  45.  
  46. // 1波長分出力
  47. line.write(b, 0, b.length);
  48.  
  49. // おおよそ2秒間鳴らしたら終了
  50. long time = System.currentTimeMillis();
  51. if (time > startTime + 2000L) {
  52. break;
  53. }
  54. }
  55.  
  56. line.drain();
  57. line.stop();
  58. }
  59. }
  60. }
  61.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty