问题
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[]
?
回答1:
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)
回答2:
Some time ago I wrote a small server to stream music over http: Stream music in loop over http using java
Go over there, and the way it plays, you just go to the specified link, i.e : www.localhost:8080/test in my case and the browser streams the music.
Maybe you could find the solution in combining some of my results with the yours' ones.
Actually, whatever link returns the bytearray, would be streamed by browser depending on the datatype, etc.
来源:https://stackoverflow.com/questions/14945217/playing-sound-from-a-byte-array