我已成功通过 TCP 套接字发送和读取文本和图像数据。但我无法发送和读取音频流数据。
服务器上的示例代码:
public class ServerAudio {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ServerSocket serverSocker = new ServerSocket();
Socket client = null;
serverSocker.bind(new InetSocketAddress(6666));
if (serverSocker.isBound()) {
client = serverSocker.accept();
OutputStream out = client.getOutputStream();
while (true) {
AudioInputStream ain = testPlay("C:/Users/Public/Music/Sample Music/adios.wav");
if (ain != null) {
AudioSystem.write(ain, AudioFileFormat.Type.WAVE, out);
}
}
}
serverSocker.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static AudioInputStream testPlay(String filename) {
AudioInputStream din = null;
try {
File file = new File(filename);
AudioInputStream in = AudioSystem.getAudioInputStream(file);
System.out.println("Before :: " + in.available());
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat =
new AudioFormat(AudioFormat.Encoding.PCM_UNSIGNED, baseFormat.getSampleRate(),
8, baseFormat.getChannels(), baseFormat.getChannels(),
baseFormat.getSampleRate(), false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
System.out.println("After :: " + din.available());
return din;
} catch (Exception e) {
// Handle exception.
e.printStackTrace();
}
return din;
}
}
客户端示例代码:
public class RDPPlayAudioBytes {
private static Socket socket;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// SocketAddress socketAddress = new InetSocketAddress("172.19.1.50", 4444);
try {
Socket socket = new Socket("172.19.0.109", 6666);
// socket.connect(socketAddress, 10000);
if (socket != null && socket.isConnected()) {
InputStream inputStream = socket.getInputStream();
// DataInputStream din=new DataInputStream(inputStream);
while (inputStream != null) {
if (inputStream.available() > 0) {
System.out.println(inputStream.available());
InputStream bufferedIn = new BufferedInputStream(inputStream);
System.out.println("********** Buffred *********" + bufferedIn.available());
AudioInputStream ais = AudioSystem.getAudioInputStream(bufferedIn);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} /*
* catch (LineUnavailableException e) { // TODO Auto-generated catch block
* e.printStackTrace(); }
*/catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我在哪里得到异常
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
我观察到服务器正在向客户端发送 35394 字节数据,但在客户端我们收到 8192 字节数据。我无法理解为什么客户端缺少字节。
请帮助我如何通过 TCP 套接字发送音频流。