鴻飛

导航

 

1.创建一个H5 <video>标签

<video id="sound" type="video/mp4" controls="controls" autoplay="autoplay"
       webkit-playsinline="true"    playsinline="true"   heigth="100%"></video>

2.创建请求获取视频源,并将视频源转为blob对象

    //创建XMLHttpRequest对象
    var xhr = new XMLHttpRequest();
    //配置请求方式、请求地址以及是否同步
    xhr.open('POST', '/armystudy/blob/getVideoSrc', true);
    //设置请求结果类型为blob
    xhr.responseType = 'blob';
    //请求成功回调函数
    xhr.onload = function(e) {
        if (this.status == 200) {//请求成功
            //获取blob对象
            var blob = this.response;
            //获取blob对象地址,并把值赋给容器
            $("#sound").attr("src", URL.createObjectURL(blob));
        }
    };
    xhr.send();

3.Java后台将视频转为视频源

   @ResponseBody
    @RequestMapping("/getVideoSrc")
    public OutputStream getVideoSrc(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse){
        //1.创建文件对象
        File f = new File("E:/test/1.mp4");
        //2.获取文件名称
        String fileName = f.getName();
        //3.导出文件
        String agent = httpServletRequest.getHeader("User-Agent").toUpperCase();
        InputStream fis = null;
        OutputStream os = null;
        try {
            //4.获取输入流
            fis = new BufferedInputStream(new FileInputStream(f.getPath()));
            byte[] buffer;
            buffer = new byte[fis.available()];
            fis.read(buffer);
            httpServletResponse.reset();
            //5.由于火狐和其他浏览器显示名称的方式不相同,需要进行不同的编码处理
            if(agent.indexOf("FIREFOX") != -1){//火狐浏览器
                httpServletResponse.addHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("GB2312"),"ISO-8859-1"));
            }else{//其他浏览器
                httpServletResponse.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            }
            //6.设置response编码
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.addHeader("Content-Length", "" + f.length());
            //设置输出文件类型
            httpServletResponse.setContentType("video/mpeg4");
            //7.获取response输出流
            os = httpServletResponse.getOutputStream();
            os.flush();
            //8.输出文件
            os.write(buffer);
        }catch(Exception e){
            System.out.println(e.getMessage());
        } finally{
            //关闭流
            try {
                if(fis != null){ fis.close(); }

                if(os != null){ os.flush(); }

                if(os != null){os.close(); }

            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }

        return os;
    }

转载:https://cloud.tencent.com/developer/article/1335832

posted on 2020-12-02 11:29  鴻飛  阅读(444)  评论(0编辑  收藏  举报