forked from cravxx/unfm2jg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SoundClipThreaded.java
80 lines (58 loc) · 1.92 KB
/
SoundClipThreaded.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import fallk.logmaster.HLogger;
import javax.sound.sampled.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class SoundClipThreaded implements Runnable, SoundClip {
private byte[] clipBytes;
boolean isPlaying = false;
boolean loaded;
public SoundClipThreaded(byte[] byteInput) {
try {
this.clipBytes = byteInput;
loaded = true;
} catch (Exception e) {
HLogger.error(e);
loaded = false;
}
}
@Override
public void play() {
if (loaded && !isPlaying) {
isPlaying = true;
try {
final byte[] data = new byte[4096];
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(clipBytes));
SourceDataLine dataLine = (SourceDataLine) AudioSystem.getLine(new DataLine.Info(SourceDataLine.class, audioInputStream.getFormat()));
if (!dataLine.isOpen()) {
dataLine.open();
dataLine.start();
int nBytesRead = 0;
while ((nBytesRead != -1)) {
nBytesRead = audioInputStream.read(data, 0, data.length);
if (nBytesRead != -1) {
dataLine.write(data, 0, nBytesRead);
}
}
dataLine.drain();
}
dataLine.stop();
dataLine.flush();
dataLine.close();
audioInputStream.close();
} catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) {
HLogger.error(e);
}
}
isPlaying = false;
}
@Override
public void loop() {
}
@Override
public void stop() {
}
@Override
public void run() {
play();
}
}