기본적으로 JAVA는 멀티미디어 쪽에 매우 많이 약하다.
그 흔한 wave 파일 재생도 꽤나 어려웠었다...
뭐, 지금도 그리 좋아보이진 않지만...
JAVA 5.0에서는 javax.sound 패키기를 추가하였다.
이 패키지를 이용하면 midi 파일과 wave 파일 재생을 할 수가 있다.
더 재생 가능한 파일 포멧이 있는지는 잘 모르겠지만...
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
while (clip.isActive()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
clip.stop();
clip.close();
audioInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
처음에는 위와 같이 작성하였다.
하지만 재생이 될 때가 있고 안 될 때가 있었다.
(파일은 단순한 wave 파일이었다.)
그래서 다음과 같이 변경하였다.
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class,audioFormat);
SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
line.open(audioFormat);
line.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0) {
line.write(abData, 0, nBytesRead);
}
}
line.drain();
line.close();
audioInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
뭐, 이렇게 하니깐 잘 재생된다...