gpt4 book ai didi

java - 使用 Ajax 和 java ReSTLet 在客户端应用程序中流式传输视频

转载 作者:行者123 更新时间:2023-12-01 12:02:23 25 4
gpt4 key购买 nike

您好,我想在客户端应用程序中流式传输视频,但视频位于服务器应用程序中。我正在使用 java ReSTLet 和 Jquery Ajax 将客户端应用程序连接到服务器应用程序。通过 Ajax 调用我连接到 ReSTLet。我不知道从服务器端流式传输视频后如何向ajax发送响应,ajax如何接收响应以及如何在浏览器中播放视频。任何人都可以帮我处理这个问题吗?

这是我的代码

HTML:

<button id="playVideo" class="btn-primary">PlayVideo</button>
<video id="videoTab" height="300" width="500" style="display: none" controls ></video>

Ajax 调用服务器

    $('#playVideo').click(function (){
var jsonObj = {};
jsonObj.userId = "siva";
jsonObj.file = "sample.mp4";
//console.log("json obje :"+ JSON.stringify(jsonObj))
// Rest call to play videos.
$.ajax({
type : 'GET',
url : config.streamVideo,
//dataType : 'json',
data : JSON.stringify(jsonObj),
contentType : "application/json",
mimeType : "video/mp4",
processData : false,
crossDomain : true,
success : function(result) {
//console.log("login result : " + JSON.stringify(result));
if (result) {
console.log("success.....");
srcPath = "data:video/mp4;"+result;
$('#videoTab').attr('src', srcPath);
$('#videoTab').css('display', 'block');
$('#videoTab').attr('autoplay', true);
} else {
alert('failed...');
}
},
error : function(){
alert('error')
}
});
});

ReSTLet代码:

@Get
public InputRepresentation handleRequest(Representation entity) throws IOException, ResourceException {
// Set response headers
Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null) {
responseHeaders = new Series<Header>(Header.class);
getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}
responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));

logger.debug("+++++++++++++++++++Entered in play video restlet +++++++++++++++");
// Convert Rest type request to Servlet request
httpServletRequest = ServletUtils.getRequest(getRequest());
// Get Servlet context object.
sc = httpServletRequest.getServletContext();
// Get input file path.
logger.debug("------->getRealPath " + sc.getRealPath("/"));
String filePath = sc.getRealPath("/") + "WEB-INF\\data\\videos\\sample.mp4";

final File file = new File(filePath);
if (file.exists()) {
logger.debug("Requested file path : " + file.getAbsolutePath());
logger.debug("inputRepresentation :" + inputRepresentation);
fis = new FileInputStream(file);
inputRepresentation = new InputRepresentation(new InputStream() {
private boolean waited = false;

@Override
public int read() throws IOException {
waited = false;

// read the next byte of the FileInputStream, when reaching the
// end of the file, wait for 2 seconds and try again, in case
// the file was not completely created yet
while (true) {
byte[] b = new byte[1];

if (fis.read(b, 0, 1) > 0) {
return b[0] + 256;
} else {
if (waited) {
return -1;
} else {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
logger.error("Exception while streaming video : ", ex);
}
waited = true;
}
}
}
}

}, MediaType.VIDEO_MP4);
} else {
logger.debug("Requested file not found : " + filePath);
}
//logger.debug("inputRepresentation :");
return inputRepresentation;
}

提前致谢

最佳答案

阅读您的评论后,这是我对您应该做什么的理解。我不会将 json 发送到资源来获取某些内容,我只会发送一个简单的 GET 请求。您需要:

  • 根据标识符返回视频文件的资源。为了便于说明,假设其网址模板是 /videos/{videoid}
  • 包含链接和空视频播放器的网页
  • 一些 javascript,使用上面定义的 url 设置“src”属性视频播放器:/videos/{videoid}。您计算videoid的方式是您自己的事。

这是服务器代码:

  • 定义 URI 模板的 ReSTLet 应用程序
@Override
public Restlet createInboundRoot() {

Router router = new Router(getContext());

// attaches the resource that represents a video, according to its identifier
router.attach("/videos/{videoid}", VideoServerResource.class);
// ... other instructions

return router;
}
  • 视频服务器资源:
public class VideoServerResource extends ServerResource {

private File video;
@Override
protected void doInit() throws ResourceException {
String videoId = getAttribute("videoid");
// Compute path
String path = "/tmp/" + videoId + ".mp4";
video = new File(path);
// takes care of not found status responses.
setExisting(video.isFile());
}

@Get("mp4")
public File represent() {
return video;
}
}

这是客户端代码。这是一个示例网页,带有一个空的视频播放器。单击按钮时,视频播放器会被要求播放 http://example.com:9000/videos/testvideo视频。在您的例子中,值testvideo只是从用户点击的链接中推导出来的。

<!DOCTYPE html> 
<html>
<head>
<script src="/static/jquery.js"></script>
<script>
$('#playVideo').click(function (){
srcPath = "http://127.0.0.1:9000/videos/testvideo";
$('#videoTab').attr('src', srcPath);
$('#videoTab').css('display', 'block');
$('#videoTab').attr('autoplay', true);
});
</script>
</head>
<body>

<button id="playVideo" class="btn-primary">PlayVideo</button>
<video id="videoTab" height="300" width="500" style="display: none" controls ></video>
</body>
</html>

希望这对您有帮助。

关于java - 使用 Ajax 和 java ReSTLet 在客户端应用程序中流式传输视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27901507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com