我正在尝试将摄像头的视频发送到服务器,然后再带回我的计算机,摄像头的视频完美地显示在第一个屏幕上,第二个屏幕上应该是相同的视频,但是收到了从服务器。我将视频很好地发送到服务器,服务器接受了该视频并将其发送回计算机。但是视频未显示在第二个屏幕上。
这是我的代码。
客户端:
<video autoplay class="video" id="video1"></video>
<video autoplay class="video" id="video2"></video>
<script type="text/javascript">
var video1, video2;
var port="<%out.write(port);%>";
var ws;
var connect=false;
switch(lang){
case "en":
text1="roll up";
text2="expand";
break;
case "ru":
text1="свернуть";
text2="развернуть";
break;
}
video1=document.querySelector('#video1');
ws = new WebSocket("ws://127.0.0.1:"+port);
ws.binaryType = 'arraybuffer';
navigator.mediaDevices.getUserMedia({ audio: true, video: {width: 400, height: 400}})
.then(stream => {
var streamChunks = [];
var outChunks = [];
video1.src = window.URL.createObjectURL(stream);
const mediaRecorder = new MediaRecorder(stream);
//запись потока в массив
mediaRecorder.addEventListener("dataavailable",function(event) {
if(connect==true){
streamChunks.push(event.data);
ws.send(streamChunks[0]);
}
streamChunks = [];
});
mediaRecorder.start();
setInterval(function() {
mediaRecorder.requestData();
}, 1000);
});
var mediaSource = new MediaSource();
var buffer;
var queue = [];
video2=document.querySelector('#video2');
ws.onopen = function(e) {
connect=true;
};
mediaSource.addEventListener('sourceopen', function(e) {
video2.play();
buffer = mediaSource.addSourceBuffer('video/webm; codecs="vorbis,vp8"');
buffer.addEventListener('update', function() { //Note: Have tried 'updateend'
if (queue.length > 0 && !buffer.updating) {
buffer.appendBuffer(queue.shift());
}
});
}, false);
video2.src=window.URL.createObjectURL(mediaSource);
ws.onmessage = function(event) {
if (event.data instanceof ArrayBuffer) {
try {
if (buffer.updating || queue.length > 0) {
queue.push(event.data);
} else {
buffer.appendBuffer(event.data);
}
} catch (e) {
console.log(e);
}
} else {
writeResponse(event.data);
}
};
</script>
服务器
package model;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Set;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class video_chat_server extends WebSocketServer {
private Set<WebSocket> conns;
public video_chat_server( int port ) throws UnknownHostException {
super( new InetSocketAddress(port) );
conns = new HashSet<>();
}
public video_chat_server( InetSocketAddress address ) {
super(address);
}
@Override
public void onMessage(WebSocket conn, ByteBuffer blob) {
// TODO Auto-generated method stub
for (WebSocket sock : conns) {
sock.send(blob);
}
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
// TODO Auto-generated method stub
if(conns.size()<2)conns.add(conn);
}
}