SpringBoot 视频流和音频流(输出到浏览器)

记录一次处理视频输出到浏览器,就像输出图片到浏览器一样效果。

如需想要图片输出到浏览器请查阅: https://blog.csdn.net/qq_16771097/article/details/124386496

第一步:添加如下设置

package com.shishi.springbootweb.config;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import javax.servlet.http.HttpServletRequest;
import java.nio.file.Path;

/**
 * @ClassName: MedioHttpRequestHandler
 * @Description: 视频流和音频流加载设置
 * @Author: Administrator
 * @Date: 2022/4/15 11:38
 */
@Component
public class MedioHttpRequestHandler extends ResourceHttpRequestHandler {
    public final static String ATTR_FILE = "NON-STATIC-FILE";

    @Override
    protected Resource getResource(HttpServletRequest request) {
        final Path filePath = (Path) request.getAttribute(ATTR_FILE);
        return new FileSystemResource(filePath);
    }
}

第二步:调用时,添加设置

package com.shishi.springbootweb.controller.common;

import com.shishi.springbootweb.config.MedioHttpRequestHandler;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @ClassName: MediaController
 * @Description: 视频文件处理
 * @Author: Administrator
 * @Date: 2022/4/14 18:14
 */
@Api(tags = "视频文件处理API")
@RestController
public class MediaController {

    String url = "E:\\z-work\\media\\";

    @Resource
    private MedioHttpRequestHandler medioHttpRequestHandler;

    /**
     * 获取视频
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("/api/media/video")
    public void getPlayResource( HttpServletRequest request, HttpServletResponse response) throws Exception {
        Path path = Paths.get(url + "上海疫情播报.mp4");
        if (Files.exists(path)) {
            String mimeType = Files.probeContentType(path);
            if (!StringUtils.isEmpty(mimeType)) {
                response.setContentType(mimeType);
            }
            request.setAttribute(MedioHttpRequestHandler.ATTR_FILE, path);
            medioHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }
}

实际效果:
在这里插入图片描述

评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值