*** empty log message ***
[thera-pi.git] / BMIRechner / src / Tools / AePlayWave.java
blob560e64ff31ddde3f571998a83f495127c8d7eb1d
1 package Tools;
3 import java.io.File;
4 import java.io.IOException;
5 import javax.sound.sampled.AudioFormat;
6 import javax.sound.sampled.AudioInputStream;
7 import javax.sound.sampled.AudioSystem;
8 import javax.sound.sampled.DataLine;
9 import javax.sound.sampled.FloatControl;
10 import javax.sound.sampled.LineUnavailableException;
11 import javax.sound.sampled.SourceDataLine;
12 import javax.sound.sampled.UnsupportedAudioFileException;
14 public class AePlayWave extends Thread {
16 private String filename;
18 private Position curPosition;
20 private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
22 enum Position {
23 LEFT, RIGHT, NORMAL
26 public AePlayWave(String wavfile) {
27 filename = wavfile;
28 curPosition = Position.NORMAL;
31 public AePlayWave(String wavfile, Position p) {
32 filename = wavfile;
33 curPosition = p;
36 public void run() {
38 File soundFile = new File(filename);
39 if (!soundFile.exists()) {
40 System.err.println("Wave file not found: " + filename);
41 return;
44 AudioInputStream audioInputStream = null;
45 try {
46 audioInputStream = AudioSystem.getAudioInputStream(soundFile);
47 } catch (UnsupportedAudioFileException e1) {
48 e1.printStackTrace();
49 return;
50 } catch (IOException e1) {
51 e1.printStackTrace();
52 return;
55 AudioFormat format = audioInputStream.getFormat();
56 SourceDataLine auline = null;
57 DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
59 try {
60 auline = (SourceDataLine) AudioSystem.getLine(info);
61 auline.open(format);
62 } catch (LineUnavailableException e) {
63 e.printStackTrace();
64 return;
65 } catch (Exception e) {
66 e.printStackTrace();
67 return;
70 if (auline.isControlSupported(FloatControl.Type.PAN)) {
71 FloatControl pan = (FloatControl) auline
72 .getControl(FloatControl.Type.PAN);
73 if (curPosition == Position.RIGHT)
74 pan.setValue(1.0f);
75 else if (curPosition == Position.LEFT)
76 pan.setValue(-1.0f);
79 auline.start();
80 int nBytesRead = 0;
81 byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
83 try {
84 while (nBytesRead != -1) {
85 nBytesRead = audioInputStream.read(abData, 0, abData.length);
86 if (nBytesRead >= 0)
87 auline.write(abData, 0, nBytesRead);
89 } catch (IOException e) {
90 e.printStackTrace();
91 return;
92 } finally {
93 auline.drain();
94 auline.close();