使用 Ajax 和 java Restlet 在客户端应用程序中流式传输视频 [英] Stream videos in client app using Ajax and java Restlet

查看:42
本文介绍了使用 Ajax 和 java Restlet 在客户端应用程序中流式传输视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的代码

HTML:

Ajax 调用服务器

 $('#playVideo').click(function (){var jsonObj = {};jsonObj.userId = "siva";jsonObj.file = "sample.mp4";//console.log("json 对象:"+ JSON.stringify(jsonObj))//播放视频的休息调用.$.ajax({类型:'获取',网址:config.streamVideo,//数据类型:'json',数据:JSON.stringify(jsonObj),contentType : "应用程序/json",mimeType : "视频/mp4",过程数据:假,跨域:真,成功:功能(结果){//console.log("登录结果:" + JSON.stringify(result));如果(结果){console.log("成功.....");srcPath = "data:video/mp4;"+result;$('#videoTab').attr('src', srcPath);$('#videoTab').css('display', 'block');$('#videoTab').attr('自动播放', true);} 别的 {alert('失败...');}},错误:函数(){警报('错误')}});});

RestletCode:

@Get公共 InputRepresentation handleRequest(Representation entity) 抛出 IOException, ResourceException {//设置响应头系列<标题>responseHeaders = (Series
) getResponse().getAttributes().get("org.restlet.http.headers");if (responseHeaders == null) {responseHeaders = new Series
(Header.class);getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);}responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));logger.debug("++++++++++++++++++++进入播放视频restlet++++++++++++++");//将 Rest 类型请求转换为 Servlet 请求httpServletRequest = ServletUtils.getRequest(getRequest());//获取 Servlet 上下文对象.sc = httpServletRequest.getServletContext();//获取输入文件路径.logger.debug("------->getRealPath " + sc.getRealPath("/"));String filePath = sc.getRealPath("/") + "WEB-INF\\data\\videos\\sample.mp4";最终文件文件 = 新文件(文件路径);如果(文件.存在()){logger.debug("请求的文件路径:" + file.getAbsolutePath());logger.debug("inputRepresentation:" + inputRepresentation);fis = new FileInputStream(file);inputRepresentation = new InputRepresentation(new InputStream() {私人布尔等待=假;@覆盖public int read() 抛出 IOException {等待=假;//读取 FileInputStream 的下一个字节,当到达//文件结束,等待2秒再试,以防万一//文件还没有完全创建而(真){字节[] b = 新字节[1];如果 (fis.read(b, 0, 1) > 0) {返回 b[0] + 256;} 别的 {如果(等待){返回-1;} 别的 {尝试 {线程睡眠(2000);} catch (InterruptedException ex) {logger.error("播放视频时出现异常:", ex);}等待=真;}}}}}, MediaType.VIDEO_MP4);} 别的 {logger.debug("未找到请求的文件:" + filePath);}//logger.debug("inputRepresentation :");返回输入表示;}

提前致谢

解决方案

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

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

这是服务器代码:

  • 定义 URI 模板的 Restlet 应用程序
<块引用>

@Override公共 Restlet createInboundRoot() {Router router = new Router(getContext());//根据其标识符附加代表视频的资源router.attach("/videos/{videoid}", VideoServerResource.class);//... 其他指令返回路由器;}

  • 视频服务器资源:
<块引用>

public class VideoServerResource extends ServerResource {私人文件视频;@覆盖protected void doInit() 抛出 ResourceException {String videoId = getAttribute("videoid");//计算路径字符串路径 = "/tmp/" + videoId + ".mp4";视频 = 新文件(路径);//处理未找到的状态响应.setExisting(video.isFile());}@Get("mp4")公共文件表示(){返回视频;}}

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

<头><script src="/static/jquery.js"></script><脚本>$('#playVideo').click(function (){srcPath = "http://127.0.0.1:9000/videos/testvideo";$('#videoTab').attr('src', srcPath);$('#videoTab').css('display', 'block');$('#videoTab').attr('自动播放', true);});<身体><button id="playVideo" class="btn-primary">PlayVideo</button><video id="videoTab" height="300" width="500" style="display: none" 控件 ></video></html>

希望对你有所帮助.

Hi I want to stream videos in client app but videos are located in server app. I am using java Restlet and Jquery Ajax to connect client app to server app. Through Ajax call i am connecting to Restlet. I don't know how to send response to ajax after streaming video from server side, how ajax receives response and how to play video in browser. Can any one help me to handle this.

Here is my code

Html:

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

Ajax Call to server

    $('#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')
            }
        });
    });

RestletCode:

@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;
}

Thanks in advance

解决方案

After reading your comment, here is my understanding of what you should do. I would not send json to a resource in order to get something, I would just send a simple GET request. You need:

  • a resource that returns the file of a video according to its identifier. For the matter of illustration, let's say its url template is /videos/{videoid}
  • a web page that contains the links, and the empty video player
  • some javascript that set the "src" attribute video player with the url defined above: /videos/{videoid}. The way you compute the videoid is your own business.

Here is the server code:

  • the Restlet application, that defines the URI templates

@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;
}

  • the video server resource:

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;
    }
}

Here is the client code. This is a sample Web page, with an empty video player. When clicking on the button, the video player is asked to play the http://example.com:9000/videos/testvideo video. In your case, the value testvideo is simply deduced from the link the user click on.

<!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>

I hope this will help you.

这篇关于使用 Ajax 和 java Restlet 在客户端应用程序中流式传输视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆