废话不多说,直接上代码:
1、编写工具类:Mp4ToTsUtils
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import org.springframework.util.StringUtils;
import lombok.extern.log4j.Log4j2;
/**
* @author zxy
* @date 2023年7月19日 上午11:11:30
* @Description : 视频文件转.ts文件工具类
*/
@Log4j2
public class Mp4ToTsUtils {
/**
* 将视频文件转换为.ts格式文件 <BR>
* ffmpeg命令:ffmpeg -i output.mp4 -c copy -map 0 -f segment -segment_time 5
* -segment_list output.m3u8 fengniao%03d.ts
*
* @param mp4FilePath 视频文件路径
* @param segmentTime 每个.ts文件的时长(秒)
* @return
*/
public static String convertVideoStreaming(String mp4FilePath, int segmentTime) {
// 创建ts文件存放目录
String newFolder = createTSFolder(mp4FilePath);
if (!StringUtils.hasLength(newFolder)) {
log.info("ts文件夹创建失败。");
return "";
}
long currTime = System.currentTimeMillis();
// 定义m3u8文件名和路径
String m3u8Path = newFolder + "/" + currTime + ".m3u8";
try {
ProcessBuilder pb = new ProcessBuilder("ffmpeg", "-i", mp4FilePath, "-c", "copy", "-map", "0", "-f",
"segment", "-segment_time", String.valueOf(segmentTime), "-segment_list", m3u8Path,
newFolder + "/" + currTime + "%04d.ts");
pb.redirectErrorStream(true);
Process process = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
log.info(line);
}
process.waitFor();
log.info("视频文件转.ts文件成功。路径:{}", m3u8Path);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
log.error("视频文件转.ts文件失败。");
m3u8Path = "";
}
return m3u8Path;
}
/**
* 创建存放ts文件的目录
*
* @param mp4FilePath 视频文件路径
* @return
*/
public static String createTSFolder(String mp4FilePath) {
String newPath = mp4FilePath + ".ts";
File file2 = new File(newPath);
if (file2.exists()) {
return newPath;
} else if (file2.mkdirs()) {
return newPath;
}
return "";
}
public static void main(String[] args) {
String mp5Path = "D:/testVedio/f50efd34.mp4";
// createTSFolder(mp5Path);
convertVideoStreaming(mp5Path, 5);
}
}
2、将生成的m3u8文件通过nginx代理出去,例如通过上述代码,生成的m3u8文件会在:D:/testJar/testVedio/f50efd34.mp4.ts/1689848121446.m3u8目录,那么nginx关键配置如下:
location /test-video/ {
alias D:/testJar/testVedio/f50efd34.mp4.ts/;
autoindex off;
}
3、前端页面代码如下,代码中的地址为nginx所在服务器的IP和端口号。
<!DOCTYPE html>
<html>
<head>
<title>TS文件播放</title>
</head>
<body>
<video id="videoPlayer" controls></video>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<script>
if (Hls.isSupported()) {
var video = document.getElementById('videoPlayer');
var hls = new Hls();
hls.loadSource('http://192.168.0.126:8084/test-video/1689848121446.m3u8'); // 将路径替换为生成的M3U8文件的URL
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, function () {
video.play();
});
}
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = 'http://192.168.0.126:8084/test-video/1689848121446.m3u8';
video.addEventListener('loadedmetadata', function () {
video.play();
});
}
</script>
</body>
</html>
后面会分享一下怎么接收OBS视频流,实现直播功能。