ReactPlayer
import React from 'react'
import ReactPlayer from 'react-player'
export default class OperationEdit extends React.Component {
render() {
return (
<ReactPlayer
className='react-player'
// url='https://stream7.iqilu.com/10339/upload_transcode/202002/18/20200218093206z8V1JuPlpe.mp4'
url='/api/baseInfo/file/videoPlayback'
width='100%'
height='100%'
playing={true}
controls
/>
)
}
}
java
@ApiOperation("视频流播放")
@RequestMapping(value = "/videoPlayback", method = RequestMethod.GET)
void videoPlayback() throws IOException;
@Override
public void videoPlayback() throws IOException {
String filepath = "C:\\Users\\admin\\Pictures\\测试视频\\16MSize.mp4";
//检查是否是Range请求
if (request.getHeader("Range") != null) {
//读取文件
File targetFile = new File(filepath);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(targetFile));
Long fileSize = targetFile.length();
//解析Range
Map<String, Integer> range = this.analyzeRange(request.getHeader("Range"), fileSize.intValue());
//设置响应头
response.setContentType("video/mp4");
response.setHeader("Content-Length", String.valueOf(fileSize.intValue()));
response.setHeader("Content-Range", "bytes " + range.get("startByte") + "-" + range.get("endByte") + "/" + fileSize.intValue());
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Accept-Ranges", "bytes");
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
//开始输出
OutputStream os = response.getOutputStream();
int length = range.get("endByte") - range.get("startByte");
System.out.println("length:" + length);
byte[] buffer = new byte[length < 1024 ? length : 1024];
in.skip(range.get("startByte"));
int i = in.read(buffer);
length = length - buffer.length;
while (i != -1) {
os.write(buffer, 0, i);
if (length <= 0) {
break;
}
i = in.read(buffer);
length = length - buffer.length;
}
os.flush();
//关闭
os.close();
in.close();
return;
}
}
/**
* 解析range,解析出起始byte(startByte)和结束byte(endBytes)
*
* @param range 请求发来的range
* @param fileSize 目标文件的大小
* @return
*/
private Map<String, Integer> analyzeRange(String range, Integer fileSize) {
String[] split = range.split("-");
Map<String, Integer> result = new HashMap<>();
if (split.length == 1) {
//从xxx长度读取到结尾
Integer startBytes = new Integer(range.replaceAll("bytes=", "").replaceAll("-", ""));
result.put("startByte", startBytes);
result.put("endByte", fileSize - 1);
} else if (split.length == 2) {
//从xxx长度读取到yyy长度
Integer startBytes = new Integer(split[0].replaceAll("bytes=", "").replaceAll("-", ""));
Integer endBytes = new Integer(split[1].replaceAll("bytes=", "").replaceAll("-", ""));
result.put("startByte", startBytes);
result.put("endByte", endBytes > fileSize ? fileSize : endBytes);
} else {
log.info("未识别的range:", range);
}
return result;
}