Java流视频高效



我正试图用Sockets为我的宠物构建一个相机应用程序。我的应用程序可以工作,但速度非常慢,FPS低,分辨率低。我已经把我能穿的都穿了,但还是很拖沓。有没有比Sockets更有效的视频传输方式?像YouTube这样的东西很有魅力。他们是怎么做到的?

这是我的摄像头服务器代码

public static void main(String[] args) throws IOException {
cam = Webcam.getDefault();
//cam.setCustomViewSizes(new Dimension(1080, 2340));
cam.setViewSize(WebcamResolution.QVGA.getSize());

cam.open();
new Thread(() -> {
try {
camThread();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
ServerSocket server = new ServerSocket(8886);
while (true) {
Socket client = server.accept();
new Thread(() -> {
handleConnection(client);
}).start();
}
}
public static void compressThread(byte[] input) throws IOException {
img = Compressor.compress(input);
}
public static void camThread() throws IOException {
while (true) {
BufferedImage bufferedImage = cam.getImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", baos);
new Thread(() -> {
try {
compressThread(baos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
public static void handleConnection(Socket client) {
try {
OutputStream os = client.getOutputStream();
InputStream is = client.getInputStream();
while (client.isConnected()) {
os.write(img);
os.flush();
while (is.available() == 0);
is.read();
}
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
try {
client.close();
}
catch (Exception e) {e.printStackTrace();}
}
}

和我的应用程序客户端

while (client.isConnected) {
while (`is`.available() == 0);
val baos = ByteArrayOutputStream()
var bytePre = 11111
while (`is`.available() != 0) {
val data = `is`.read()
baos.write(data)
if (data == -39) if (bytePre == -1) break
bytePre = data
}

Thread {
val bytes = baos.toByteArray()
val bm = BitmapFactory.decodeByteArray(Compressor.decompress(bytes), 0, bytes.size)
runOnUiThread { video.setImageBitmap(bm) }
}.start()
val os = client.getOutputStream()
os.write(0)
os.flush()

}
runOnUiThread { Toast.makeText(this, "Verbindung wurde geschlossen", Toast.LENGTH_LONG).show() }

您不应该按字节读取,我认为等待传入字节的繁忙循环可以使用Thread.sleep(10)来减轻CPU的压力。

尝试在read()中使用is.available()的结果。

关于可以使用的实现,请参见此处的答案:

如何在服务器套接字JAVA 中读取所有输入流

最新更新