00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 package com.realtime.crossfire.jxclient.sound;
00023
00024 import com.realtime.crossfire.jxclient.util.DebugWriter;
00025 import java.io.IOException;
00026 import javax.sound.sampled.AudioInputStream;
00027 import javax.sound.sampled.AudioSystem;
00028 import javax.sound.sampled.Clip;
00029 import javax.sound.sampled.DataLine;
00030 import javax.sound.sampled.Line;
00031 import javax.sound.sampled.LineUnavailableException;
00032 import javax.sound.sampled.UnsupportedAudioFileException;
00033 import org.jetbrains.annotations.NotNull;
00034 import org.jetbrains.annotations.Nullable;
00035
00040 public class ClipCache {
00041
00045 @NotNull
00046 private final AudioFileLoader audioFileLoader;
00047
00052 @Nullable
00053 private final DebugWriter debugSound;
00054
00061 public ClipCache(@NotNull final AudioFileLoader audioFileLoader, @Nullable final DebugWriter debugSound) {
00062 this.audioFileLoader = audioFileLoader;
00063 this.debugSound = debugSound;
00064 }
00065
00072 @Nullable
00073 public DataLine allocateClip(@Nullable final String name, @NotNull final String action) {
00074 return newClip(name, action);
00075 }
00076
00081 public void freeClip(@NotNull final Line clip) {
00082 if (debugSound != null) {
00083 debugSound.debugProtocolWrite("freeClip: "+System.identityHashCode(clip));
00084 }
00085 clip.close();
00086 }
00087
00094 @Nullable
00095 private DataLine newClip(@Nullable final String name, @NotNull final String action) {
00096 try {
00097 final AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFileLoader.getInputStream(name, action));
00098 try {
00099 final Clip clip = AudioSystem.getClip();
00100 try {
00101 clip.open(audioInputStream);
00102 } catch (final IllegalArgumentException ex) {
00103 throw new UnsupportedAudioFileException(ex.getMessage());
00104 }
00105 if (debugSound != null) {
00106 debugSound.debugProtocolWrite("newClip: "+System.identityHashCode(clip)+" "+name+"/"+action);
00107 }
00108 return clip;
00109 } finally {
00110 audioInputStream.close();
00111 }
00112 } catch (final UnsupportedAudioFileException ex) {
00113 if (debugSound != null) {
00114 debugSound.debugProtocolWrite("newClip["+name+"/"+action+"]: "+ex.getMessage());
00115 }
00116 return null;
00117 } catch (final LineUnavailableException ex) {
00118 if (debugSound != null) {
00119 debugSound.debugProtocolWrite("newClip["+name+"/"+action+"]: "+ex.getMessage());
00120 }
00121 return null;
00122 } catch (final IOException ex) {
00123 if (debugSound != null) {
00124 debugSound.debugProtocolWrite("newClip["+name+"/"+action+"]: "+ex.getMessage());
00125 }
00126 return null;
00127 }
00128 }
00129
00130 }