1 package hayashi.yuu.tools.sound;
4 import java.io.IOException;
6 import javax.sound.sampled.AudioFormat;
7 import javax.sound.sampled.AudioInputStream;
8 import javax.sound.sampled.AudioSystem;
9 import javax.sound.sampled.DataLine;
10 import javax.sound.sampled.LineUnavailableException;
11 import javax.sound.sampled.SourceDataLine;
12 import javax.sound.sampled.UnsupportedAudioFileException;
15 * サウンドファイルを再生して、音(音楽)を鳴らす。
20 public class PlaySound extends Thread
22 //static final String WAVE = "lib/belltree.aiff";
23 static String WAVE = null;
26 * サウンドファイルを再生して、音(音楽)を鳴らす。
27 * (1) PlaySound(sound file);
28 * 再生するサウンドファイルを指定して、インスタンスを生成する。
29 * サウンドファイルを指定しなければ、「BEEP」音が再生される。
30 * (2) playSound.start();
35 public static void main(String[] args) {
40 PlaySound obj = new PlaySound(null);
41 for (int i=0; i < 5; i++) {
44 } catch (IllegalThreadStateException e) {}
46 Thread.sleep(1000); // 1秒間停止
47 } catch (InterruptedException e) {}
58 PlaySound obj = new PlaySound("lib/belltree.aiff");
59 for (int i=0; i < 5; i++) {
62 } catch (IllegalThreadStateException e) {}
64 Thread.sleep(1000); // 1秒間停止
65 } catch (InterruptedException e) {}
73 private static final int EXTERNAL_BUFFER_SIZE = 128000;
74 private static AudioInputStream audioInputStream = null;
75 private static AudioFormat audioFormat = null;
80 * @throws IOException 例外
81 * @throws UnsupportedAudioFileException 例外
82 * @throws LineUnavailableException 例外
84 public PlaySound(String path) throws IOException, UnsupportedAudioFileException, LineUnavailableException {
86 PlaySound.WAVE = path;
87 if (PlaySound.WAVE != null) {
88 File soundFile = new File(PlaySound.WAVE);
89 PlaySound.audioInputStream = AudioSystem.getAudioInputStream(soundFile);
90 PlaySound.audioFormat = PlaySound.audioInputStream.getFormat(); // オーディオ形式
96 if (PlaySound.WAVE == null) {
97 java.awt.Toolkit.getDefaultToolkit().beep();
101 // データラインの情報オブジェクトを生成
102 DataLine.Info info = new DataLine.Info(SourceDataLine.class, PlaySound.audioFormat);
104 // 指定されたデータライン情報に一致するラインを取得します
105 SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
107 // 指定されたオーディオ形式でラインを開きます
108 line.open(PlaySound.audioFormat);
110 // ラインでのデータ入出力を可能にします
114 byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
115 while (nBytesRead != -1) {
116 // オーディオストリームからデータを読み込みます
117 nBytesRead = PlaySound.audioInputStream.read(abData, 0, abData.length);
118 if (nBytesRead >= 0) {
119 // オーディオデータをミキサーに書き込みます
120 line.write(abData, 0, nBytesRead);
124 // ラインからキューに入っているデータを排出します
128 catch (Exception e) {