23 package com.realtime.crossfire.jxclient.sound;
25 import java.io.IOException;
26 import javax.sound.sampled.AudioFormat;
27 import javax.sound.sampled.AudioFormat.Encoding;
28 import javax.sound.sampled.AudioInputStream;
29 import javax.sound.sampled.AudioSystem;
30 import javax.sound.sampled.LineUnavailableException;
31 import javax.sound.sampled.SourceDataLine;
32 import javax.sound.sampled.UnsupportedAudioFileException;
33 import org.jetbrains.annotations.NotNull;
61 private final CharSequence
name;
97 state = fadeOut ? 2 : 4;
105 final SourceDataLine sourceDataLine = AudioSystem.getSourceDataLine(audioInputStream.getFormat());
106 final AudioFormat audioFormat = sourceDataLine.getFormat();
108 if (audioFormat.getChannels() > 2) {
109 System.err.println(
"music "+
name+
": cannot handle more than two channels");
112 if (audioFormat.getEncoding() != Encoding.PCM_SIGNED) {
113 System.err.println(
"music "+
name+
": encoding must be PCM_SIGNED");
116 if (audioFormat.getSampleSizeInBits() != 16) {
117 System.err.println(
"music "+
name+
": sample size must be 16 bits");
120 if (audioFormat.isBigEndian()) {
121 System.err.println(
"music "+
name+
": cannot handle little endian encoding");
125 sourceDataLine.open(audioInputStream.getFormat());
127 sourceDataLine.start();
129 final byte[] buf =
new byte[8192];
130 while (
state < 3 && !Thread.currentThread().isInterrupted()) {
131 int len = audioInputStream.read(buf, 0, buf.length);
134 if (!newAudioInputStream.getFormat().matches(audioInputStream.getFormat())) {
135 newAudioInputStream.close();
136 System.err.println(
"music "+
name+
": file format has changed");
139 final AudioInputStream oldAudioInputStream = audioInputStream;
140 audioInputStream = newAudioInputStream;
141 oldAudioInputStream.close();
142 len = audioInputStream.read(buf, 0, buf.length);
144 System.err.println(
"music "+
name+
": cannot re-read file");
149 for (
int i = 0; i+3 < len &&
state < 3; i += 4) {
171 throw new AssertionError();
178 sourceDataLine.write(buf, 0, len);
181 sourceDataLine.drain();
184 sourceDataLine.stop();
187 sourceDataLine.close();
190 audioInputStream.close();
192 }
catch (
final IOException|LineUnavailableException|UnsupportedAudioFileException ex) {
193 System.err.println(
"music "+
name+
": "+ex.getMessage());
203 final float value = (short)((buf[i]&0xFF)+(buf[i+1]&0xFF)*0x100)*
volume*
MAX_VOLUME;
204 final short s = (short)value;
207 buf[i+1] = (byte)(s/0x100);
210 buf[i+1] = (byte)((s+0x10000)/0x100);
223 final AudioFormat baseFormat = rawInputStream.getFormat();
224 final AudioFormat decodedFormat =
new AudioFormat(Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels()*2, baseFormat.getSampleRate(),
false);
225 return AudioSystem.getAudioInputStream(decodedFormat, rawInputStream);