Play sound from byte array []
I got the byte array from the server and I know it connects and dispatches just fine. This is when I try to play a sound from a byte array.
This is where I have to play the sound.
SourceDataLine speaker = null;
try {
DataLine.Info speakerInfo = new DataLine.Info(SourceDataLine.class, getAudioFormat(samplerate));
speaker = (SourceDataLine) AudioSystem.getLine(speakerInfo);
} catch (LineUnavailableException e) {
e.printStackTrace();
}
int nBytesRead = 0;
while (nBytesRead != -1) {
if (nBytesRead >= 0) {
speaker.write(bytes, 0, nBytesRead);
}
}
getAudioFormat:
private AudioFormat getAudioFormat(float sample) {
int sampleSizeBits = 16;
int channels = 1;
boolean signed = true;
boolean bigEndian = false;
return new AudioFormat(sample, sampleSizeBits, channels, signed, bigEndian);
}
How to play music from byte[]
?
source to share
I can't see where you are reading from the audio byte array in the while loop. They, as you set up, should be something like this:
while (nBytesRead = soundDataArray.read(bytes) != 1)
... assuming you have a read method set so that a buffer called "bytes" receives data from the read command. Then the write () method will have "bytes" that are refilled for sending.
Of course, "bytes" is just a buffer that is only used in the while loop, not in the byte array with the original sound.
Sometimes the read method has two inputs, for example: .read(bufferArray, bytesToRead);
where values in the range of k or several k are common. (bufferArray.length == bytesToRead)
source to share
A while ago I wrote a small server for streaming music over http: Stream music in a loop over http using java
Go there and how it plays, you just go to the specified link, that is: www.localhost: 8080 / test in my case and the browser is streaming the music.
Perhaps you could find a solution that combines some of my results with yours.
Actually, any link returns bytearray, will be passed by the browser depending on the data type, etc.
source to share