Skip to content

Commit a59f9fa

Browse files
committed
Handle audio buffer overruns better
1 parent a852454 commit a59f9fa

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

src/main/java/net/raphimc/noteblocktool/audio/soundsystem/impl/JavaxSoundSystem.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,20 +77,27 @@ public synchronized void writeSamples() {
7777
playingSound.render(mutationBuffer);
7878
playingSound.write(samples, outputBuffer);
7979
}
80-
this.dataLine.write(this.writeNormalized(samples), 0, samples.length * 2);
8180
this.playingSounds.removeIf(SoundInstance::isFinished);
81+
82+
if (this.dataLine.available() < samples.length * 2) {
83+
// In case of buffer overrun, flush the queued samples
84+
this.dataLine.flush();
85+
}
86+
this.dataLine.write(this.writeNormalized(samples), 0, samples.length * 2);
8287
}
8388

8489
@Override
8590
public synchronized void stopSounds() {
91+
this.dataLine.stop();
8692
this.dataLine.flush();
93+
this.dataLine.start();
8794
this.playingSounds.clear();
8895
this.volumeDividers = null;
8996
}
9097

9198
@Override
9299
public synchronized void close() {
93-
this.dataLine.stop();
100+
this.dataLine.close();
94101
}
95102

96103
@Override

src/main/java/net/raphimc/noteblocktool/audio/soundsystem/impl/MultithreadedJavaxSoundSystem.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,10 @@ public MultithreadedJavaxSoundSystem(final int maxSounds, final float playbackSp
9292
public synchronized void writeSamples() {
9393
this.soundsToRender.addAll(this.playingSounds);
9494
this.syncLock.set(this.playingSounds.size());
95-
9695
while (this.syncLock.get() != 0 && !Thread.currentThread().isInterrupted()) {
9796
// Wait for all sounds to be rendered and merged
9897
}
98+
this.playingSounds.removeIf(SoundInstance::isFinished);
9999

100100
final long[] samples = new long[this.samplesPerTick];
101101
for (long[] threadSamples : this.threadSamples) {
@@ -104,8 +104,11 @@ public synchronized void writeSamples() {
104104
}
105105
Arrays.fill(threadSamples, 0);
106106
}
107+
if (this.dataLine.available() < samples.length * 2) {
108+
// In case of buffer overrun, flush the queued samples
109+
this.dataLine.flush();
110+
}
107111
this.dataLine.write(this.writeNormalized(samples), 0, samples.length * 2);
108-
this.playingSounds.removeIf(SoundInstance::isFinished);
109112
}
110113

111114
@Override

0 commit comments

Comments
 (0)