-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaveThread.java
More file actions
53 lines (47 loc) · 1.55 KB
/
WaveThread.java
File metadata and controls
53 lines (47 loc) · 1.55 KB
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
package com.game.main;
import javax.sound.sampled.*;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
/**
* 用于播放音效的线程
*
* @author 洛玖
* @version 1.0
* @date 2018/07/25
*/
public class WaveThread extends Thread {
private String filename;
private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
public WaveThread(String wavfile) {
filename = wavfile;
}
public void run() {
AudioInputStream audioInputStream = null;
SourceDataLine auline = null;
URL url = Thread.currentThread().getContextClassLoader().getResource(filename);
try {
File soundFile = new File(url.toURI());
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
AudioFormat format = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (auline != null) {
auline.drain();
auline.close();
}
}
}
}