📄 soundplay.java
字号:
package Sound;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import Commen.BufferStream;
public class SoundPlay extends Thread {
AudioFormat audioFormat = null;
SourceDataLine sourceDataLine = null;
DataLine.Info dataLineInfo = null;
BufferStream bufferStream = null;
boolean isPlaying = false;
public SoundPlay(byte[] buffer) {
try {
bufferStream = new BufferStream(15000);
audioFormat = new AudioFormat(20000, 16, 2, true, true);
bufferStream.puts(buffer);
dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
sourceDataLine = (SourceDataLine) (AudioSystem
.getLine(dataLineInfo));
} catch (Exception ex) {
ex.printStackTrace();
}
}
public SoundPlay() {
try {
bufferStream = new BufferStream(15000);
audioFormat = new AudioFormat(20000, 16, 2, true, true);
dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
sourceDataLine = (SourceDataLine) (AudioSystem
.getLine(dataLineInfo));
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void StopPlaying() {
try {
System.out.println("StopPlaying");
isPlaying = false;
sourceDataLine.stop();
sourceDataLine.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void StartPlaying() {
try {
System.out.println("StartPlaying");
isPlaying = true;
sourceDataLine.open(audioFormat, sourceDataLine.getBufferSize());
sourceDataLine.start();
super.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void Append(byte[] add) {
synchronized (bufferStream) {
bufferStream.puts(add);
}
}
public void run() {// 从流中读 写入管子 写入管子就是放音的过程
try {
byte[] buffer;
while (isPlaying) {
synchronized (bufferStream) {
buffer = bufferStream.gets();
}
// System.out.println(buffer == null);
if (buffer == null)// 缓冲区里没有东西
continue;
sourceDataLine.write(buffer, 0, buffer.length);
}
System.out.println("StopPlaying");
isPlaying = false;
} catch (Exception ex) {
ex.printStackTrace();
}
}
public boolean IsPlaying() {
return isPlaying;
}
public int Remain() {
return bufferStream.Remain();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -