我正在尝试使用TCP
通过Java中的Java sound api
套接字流音频。
好吧,问题出在客户端将播放来自服务器的数据缓冲区时,进入播放方法时,会自动显示以下错误:
Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1121)
at AudioClient.play(AudioClient.java:37)
at AudioClient.main(AudioClient.java:18)
我不知道他为什么显示它,或者我做错了。
这是服务器代码,它查找文件并将其发送给客户端
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class AudioServer {
public static void main(String[] args) throws IOException {
File soundFile = AudioUtil.getSoundFile("C:\\Users\\Carlos\\Desktop\\03- Walk.wav");
System.out.println("server: " + soundFile);
try (ServerSocket serverSocker = new ServerSocket(6666);
FileInputStream in = new FileInputStream(soundFile)) {
if (serverSocker.isBound()) {
Socket client = serverSocker.accept();
OutputStream out = client.getOutputStream();
byte buffer[] = new byte[2048];
int count;
while ((count = in.read(buffer)) != -1)
out.write(buffer, 0, count);
}
}
System.out.println("server: shutdown");
}
}
这是客户端代码,它捕获并复制数据流
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.Socket;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class AudioClient {
public static void main(String[] args) throws Exception {
// play soundfile from server
System.out.println("Client: reading from 192.168.0.19:6666");
try (Socket socket = new Socket("192.168.0.19", 6666)) {
if (socket.isConnected()) {
InputStream in = new BufferedInputStream(socket.getInputStream());
play(in);
}
}
System.out.println("Client: end");
}
private static synchronized void play(final InputStream in) throws Exception {
AudioInputStream ais = AudioSystem.getAudioInputStream(in);
try (Clip clip = AudioSystem.getClip()) {
clip.open(ais);
clip.start();
Thread.sleep(100); // given clip.drain a chance to start
clip.drain();
}
}
}
此外,还有一个AudioUtils
类,该类仅包含一个静态方法,该静态方法仅在程序员传递的文件不是文件或不存在的情况下引发异常。代码如下
import java.io.File;
public class AudioUtil {
public static File getSoundFile(String fileName) {
File soundFile = new File(fileName);
if (!soundFile.exists() || !soundFile.isFile())
throw new IllegalArgumentException("not a file: " + soundFile);
return soundFile;
}
}
还应该澄清的是,服务器和控制器这两个类都具有proncipal方法,因为它们是2个独立的程序。我的问题是,如何解决此错误,我真的不知道从哪里开始。谢谢