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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
|
public class OutputProcessToLine extends Processor {
private final ManagerBuffer managerBuffer;
class ManagerBuffer {
byte[] buffer = new byte[sampleRate/2];
int bfIdx = 0;
public byte[] addToBuffer(byte[] buffer4) {
if (bfIdx < buffer.length - buffer4.length) {
for (int i = 0; i < buffer4.length; i++)
buffer[bfIdx++] = buffer4[i];
return null;
} else {
byte[] copy =
Arrays.copyOf(buffer, bfIdx);
bfIdx = 0;
return copy;
}
}
}
private double amplitudeMax;
private byte[] nextBuffer ;
private AudioFormat af;
private SourceDataLine sdl;
boolean isBigEndian = false;
boolean isSigned = true;
int bits = 16;
int channels = 1;
int sampleRate = 44100;
long offset = 0;
public void run() {
af = new AudioFormat(sampleRate, bits, channels, isSigned, isBigEndian);
try {
// 44,100 samples per second, 16-bit audio, mono, signed PCM, little
// Endian
DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
sdl = (SourceDataLine)AudioSystem.getLine(info);
sdl.open(af, 44100 * 16);
} catch (LineUnavailableException e) {
System.out.println(e.getMessage());
}
// no sound gets made before this call
sdl.start();
while (isRunning()) {
long samplesCount = 0;
if (values.size() > 400) {
while(values.size()>0 && samplesCount<400)
{
double v = values.removeFirst();
byte[] nullOrBufferToPlay = addToBufferMono(v);
if (nullOrBufferToPlay != null) {
offset+=nullOrBufferToPlay.length;
try {
sdl.write(nullOrBufferToPlay, 0, nullOrBufferToPlay.length);
} catch (Exception ex) {
ex.printStackTrace();
}
samplesCount++;
if (samplesCount % sampleRate == 0)
System.out.println("output runs");
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
samplesCount=0;
}
}
end();
}
byte[] addToBufferMono(double v) {
double aD = (amplitudeMax * v);
short a = (short) aD;
if(nextBuffer.length==2) {
nextBuffer[0] = (byte) (a & 0x00FF);
nextBuffer[1] = (byte) ((a & 0xFF00) >> 8);
}
if(nextBuffer.length==4) {
nextBuffer[2] = (byte) (a & 0x00FF);
nextBuffer[3] = (byte) ((a & 0xFF00) >> 8);
}
return managerBuffer.addToBuffer(nextBuffer);
}
public OutputProcessToLine(double amplitudeMax) {
this.amplitudeMax = amplitudeMax;
managerBuffer = new ManagerBuffer();
nextBuffer = new byte[channels*2];
System.out.println("output start");
}
public void end() {
sdl.drain();
sdl.stop();
}
} |
Partager