Swing/Sound のバックアップ(No.35)
- バックアップ一覧
 - 差分 を表示
 - 現在との差分 を表示
 - 現在との差分 - Visual を表示
 - ソース を表示
 - Swing/Sound へ行く。
  
- 1 (2004-11-04 (木) 10:11:14)
 - 2 (2005-04-28 (木) 04:33:09)
 - 3 (2005-09-11 (日) 15:58:38)
 - 4 (2006-02-27 (月) 16:27:32)
 - 5 (2006-04-01 (土) 04:12:36)
 - 6 (2007-03-28 (水) 20:17:17)
 - 7 (2007-10-11 (木) 12:48:48)
 - 8 (2007-12-06 (木) 04:13:55)
 - 9 (2007-12-06 (木) 10:11:58)
 - 10 (2007-12-08 (土) 01:07:49)
 - 11 (2007-12-08 (土) 14:33:41)
 - 12 (2007-12-12 (水) 01:47:53)
 - 13 (2007-12-12 (水) 14:10:06)
 - 14 (2007-12-12 (水) 15:53:36)
 - 15 (2007-12-17 (月) 06:46:45)
 - 16 (2007-12-17 (月) 11:39:04)
 - 17 (2008-11-21 (金) 11:57:41)
 - 18 (2012-10-15 (月) 17:29:22)
 - 19 (2012-10-15 (月) 18:53:34)
 - 20 (2013-04-11 (木) 22:01:02)
 - 21 (2015-10-14 (水) 15:29:33)
 - 22 (2016-06-24 (金) 16:32:43)
 - 23 (2016-08-26 (金) 14:37:26)
 - 24 (2016-09-02 (金) 12:29:44)
 - 25 (2017-10-17 (火) 15:17:16)
 - 26 (2019-05-04 (土) 21:39:07)
 - 27 (2019-07-01 (月) 19:40:30)
 - 28 (2019-07-04 (木) 14:59:22)
 - 29 (2021-03-14 (日) 19:51:22)
 - 30 (2025-01-03 (金) 08:57:02)
 - 31 (2025-01-03 (金) 09:01:23)
 - 32 (2025-01-03 (金) 09:02:38)
 - 33 (2025-01-03 (金) 09:03:21)
 - 34 (2025-01-03 (金) 09:04:02)
 - 35 (2025-06-19 (木) 12:41:37)
 - 36 (2025-06-19 (木) 12:43:47)
 
 
- category: swing
folder: Sound
title: Wavファイルの演奏
tags: [AudioSystem, Sound]
author: aterai
pubdate: 2004-08-16T00:28:04+09:00
description: AudioSystemを使って、AudioInputStream、Clip(Line)などを作成取得し、wavファイルを演奏します。
image: 

 
Summary
AudioSystemを使って、AudioInputStream、Clip(Line)などを作成取得し、wavファイルを演奏します。
Screenshot

Advertisement
Source Code Examples
URL url = getClass().getResource("notice1.wav");
try (AudioInputStream sound = AudioSystem.getAudioInputStream(url);
     Clip clip = (Clip) AudioSystem.getLine(new DataLine.Info(Clip.class, sound.getFormat()))) {
  SecondaryLoop loop = Toolkit.getDefaultToolkit().getSystemEventQueue().createSecondaryLoop();
  clip.addLineListener(e -> {
    LineEvent.Type t = e.getType();
    if (Objects.equals(t, LineEvent.Type.STOP) || Objects.equals(t, LineEvent.Type.CLOSE)) {
      loop.exit();
    }
  });
  clip.open(sound);
  clip.start();
  loop.enter();
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
  ex.printStackTrace();
  Toolkit.getDefaultToolkit().beep();
}
View in GitHub: Java, KotlinExplanation
AudioSystemを使用すれば、WAVE、AU、AIFF、SND形式のサウンドファイルが演奏可能です。
AudioInputStreamやClipをAutoCloseableで自動的に開放するためtry-with-resourcesブロックで作成- 演奏開始後に
SecondaryLoopで現在のスレッドをブロックし新しいセカンダリイベントループで演奏を継続 - 演奏終了イベントを
LineListenerで受け取るとセカンダリイベントループを終了して現在のスレッドに戻りclose()が自動的に実行される 
Reference
- AudioSystem (Java Platform SE 8)
 "taitai studio" フリーWav素材集上記のサイトのサイトが移転しているようなので、別の素材を探す予定wavファイルをサンプルとして利用しています。
- MIDIファイルの演奏
 - Beep音を鳴らす
 - AuditoryCuesでイベント音を設定する