JAVA如何实现视频在线播放(MP4文件在线播放)

不需要web端进行操作,即可直接进行播放,话不多说,直接上代码!

  1. Controller代码
/**
     * @description: MP4文件在线播放
     * @author: Re、ZOO2
     * @date: 2021/7/25 22:55
     * @param: [request, response, floderPath文件夹路径, fileName文件名称]
     * @return: com.lvmvp.configconsts.constant.ResultView
    **/
    @GetMapping(value = "/playMp4/{fileName}",produces ="application/json;charset=utf-8")
    public ResultView playMp4(HttpServletRequest request, HttpServletResponse response,
                              @PathVariable("fileName") String fileName){
        String floderPath = "D:/Desktop/";
        FileNormalOperationUtils.aloneVideoPlay(request,response,floderPath,fileName);
        return null;
    }
  1. FileNormalOperationUtils工具类方法调用
/**
     * @description: 在线播放MP4文件
     * @author: Re、ZOO2
     * @date: 2021/7/25 22:50
     * @param: [request, floderPath 文件夹路径, fileName 文件名称, response]
     * @return: void
    **/
    public static void aloneVideoPlay(HttpServletRequest request, HttpServletResponse response,String floderPath, String fileName) {
        InputStream is = null;
        OutputStream os = null;
        try {
            response.setContentType("video/mp4");
            File file = new File(floderPath + fileName);
            response.addHeader("Content-Length", "" + file.length());
            is = new FileInputStream(file);
            os = response.getOutputStream();
            IOUtils.copy(is, os);
        } catch (Exception e) {
            log.error("播放MP4失败", e);
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

这里只支持对MP4格式视频的播放,其他格式的需要大家进行转换后才可进行播放,格式转换可以使用格式工具进行转换。
格式化工厂友情链接: https://www.onlinedown.net/soft/577649.htm
经过个人实际确认,功能确已实现,希望对大家有用。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐