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

发布时间 2023-09-07 17:41:10作者: 宿命srl

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  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();
                }
            }
        }
    }
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

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