/* * ################################################## * # # * # SoundPlayer # * # A class for playing OGG audio with Java # * # # * # Copyright (C) by René Knipschild # * # # * # email@rkcsd.com # * # www.customsoftwaredevelopment.de # * # # * ################################################## * * File: SoundPlayer.java * Version: 1.0.4 * Last modified: 2008/07/24 10:52 CEST * Author: René Knipschild * * ===Notes========================================== * There are currently no notes. * ================================================== */ import java.io.IOException; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; public class SoundPlayer extends Thread { private String filename; private boolean loop; private AudioInputStream stream; private DataLine.Info info; private SourceDataLine line; private boolean continuePlayback; public SoundPlayer(String filename, boolean loop) { this.filename = filename; this.loop = loop; this.continuePlayback = true; } public void run() { this.setName("SoundPlayer"); try { do { this.stream = AudioSystem.getAudioInputStream(ClassLoader.getSystemResource(this.filename)); this.info = new DataLine.Info(SourceDataLine.class, this.stream.getFormat(), ((int) this.stream.getFrameLength() * this.stream.getFormat().getFrameSize())); this.line = (SourceDataLine) AudioSystem.getLine(this.info); int len = 0; int count = 1024 * this.stream.getFormat().getFrameSize(); byte[] buffer = new byte[count]; this.line.open(this.stream.getFormat()); this.line.start(); while ((len = this.stream.read(buffer, 0, count)) != -1) { this.line.write(buffer, 0, len); if (!this.continuePlayback) { break; } } if (this.continuePlayback) { this.line.drain(); } this.line.stop(); this.line.close(); } while (this.loop && this.continuePlayback); } catch (UnsupportedAudioFileException exception) { exception.printStackTrace(); } catch (IOException exception) { exception.printStackTrace(); } catch (LineUnavailableException exception) { exception.printStackTrace(); } } public void exit() { this.continuePlayback = false; } }