diff --git a/Mage.Client/src/main/java/mage/client/util/audio/MageClip.java b/Mage.Client/src/main/java/mage/client/util/audio/MageClip.java index dc64781feef..81622fe2fa1 100644 --- a/Mage.Client/src/main/java/mage/client/util/audio/MageClip.java +++ b/Mage.Client/src/main/java/mage/client/util/audio/MageClip.java @@ -28,8 +28,13 @@ package mage.client.util.audio; +import org.apache.log4j.Logger; + +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; @@ -40,30 +45,36 @@ import javax.sound.sampled.UnsupportedAudioFileException; * @author LevelX2 */ public class MageClip { + private static final Logger log = Logger.getLogger(MageClip.class); private final AudioGroup audioGroup; - private String filename; - private byte buf[]; + private final String filename; + private final byte buf[]; public MageClip(String filename, AudioGroup audioGroup) { this.filename = filename; this.audioGroup = audioGroup; - loadStream(); + this.buf = loadStream(); } - private void loadStream() { + private byte[] loadStream() { File file = new File(filename); try { AudioInputStream soundIn = AudioSystem.getAudioInputStream(file); - byte tmp[] = new byte[(int) file.length()]; - int read = 0; - read = soundIn.read(tmp, 0, tmp.length); - buf = new byte[read]; - System.arraycopy(tmp, 0, buf, 0, read); // truncate the buffer to the actual audio size - } catch (UnsupportedAudioFileException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + copy(soundIn, bytesOut); + return bytesOut.toByteArray(); + } catch (UnsupportedAudioFileException | IOException e) { + log.warn("Failed to read " + filename, e); + return null; + } + } + + private static void copy(InputStream source, OutputStream sink) throws IOException { + byte[] buf = new byte[1024]; + int n; + while ((n = source.read(buf)) > 0) { + sink.write(buf, 0, n); } } @@ -71,7 +82,7 @@ public class MageClip { return audioGroup; } - public byte[] getBuffer(){ + public byte[] getBuffer() { return buf; }