@@ -28,10 +28,12 @@ class SoundChip implements Serializable {
2828 public static final int WAVE = 2 ;
2929 public static final int NOISE = 3 ;
3030
31- private transient SourceDataLine sourceDL ;
31+ transient SourceDataLine sourceDL ;
3232
33- byte [] masterBuffer = new byte [2 * SAMPLES_PER_FRAME ];
34- byte [] tempBuffer = new byte [SAMPLES_PER_FRAME ];
33+ byte [] masterBuffer = new byte [6 * SAMPLES_PER_FRAME ];
34+ byte [] tempBuffer = new byte [3 * SAMPLES_PER_FRAME ];
35+
36+ long totalSamplesWritten = 0 ;
3537
3638 boolean [] leftEnabled = new boolean [4 ];
3739 boolean [] rightEnabled = new boolean [4 ];
@@ -40,16 +42,13 @@ class SoundChip implements Serializable {
4042 Arrays .fill (rightEnabled , true );
4143 }
4244
43- private void readObject (ObjectInputStream in ) throws IOException , ClassNotFoundException {
44- in .defaultReadObject ();
45-
46- try {
47- sourceDL = AudioSystem .getSourceDataLine (AUDIO_FORMAT );
48- sourceDL .open (AUDIO_FORMAT );
49- sourceDL .start ();
50- } catch (LineUnavailableException e ) {
51- e .printStackTrace ();
52- }
45+ public void setSourceDL (SourceDataLine sourceDL ){
46+ this .sourceDL = sourceDL ;
47+ this .totalSamplesWritten = sourceDL .getLongFramePosition ();
48+ }
49+
50+ public SourceDataLine getSourceDL (){
51+ return this .sourceDL ;
5352 }
5453
5554 SoundChip () {
@@ -82,7 +81,10 @@ public void tick() {
8281 e .printStackTrace ();
8382 }
8483 }
85- int samplesToWrite = Math .min (sourceDL .available () / 3 , SAMPLES_PER_FRAME );
84+ long residualSamples = totalSamplesWritten - sourceDL .getLongFramePosition ();
85+ int samplesToWrite = Math .max (0 , (int )(3 * SAMPLES_PER_FRAME - residualSamples )); //try to keep 3 frames buffered at all times
86+ samplesToWrite = Math .min (sourceDL .available () / 2 , Math .min (3 * SAMPLES_PER_FRAME , samplesToWrite )); //never want to block here
87+ totalSamplesWritten += samplesToWrite ;
8688
8789 Arrays .fill (masterBuffer , (byte ) 0 );
8890
0 commit comments