I've recieved a byte array from the server and I know that connects and sends perfectly. It's when I try and play the sound from the byte array.
Here's what 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 can I play music from a byte[]?
I don't see where you are reading from your sound byte array in your while loop. They way you are set up, there should probably be something along these lines:
while (nBytesRead = soundDataArray.read(bytes) != 1)
...assuming you have the read method set up so that the buffer called 'bytes' receives the data from the read command. Then the write() method will have 'bytes' repeatedly populated to send.
Of course, 'bytes' is just a buffer only used in the while loop, NOT the byte array with the source sound.
Sometimes the read method has two inputs, as in: .read(bufferArray, bytesToRead);
where values in the range of a k or several k are common. (bufferArray.length == bytesToRead)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With