为了加快加载视频的速度,我们都把视频处理成m3u8格式,然后再存放到腾讯云。
目前只是在本地跑测试代码,本地系统是windows,所以代码也只在windows上跑通。linux的需要做相应改动。上代码:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PrintStream extends Thread {
java.io.InputStream __is = null;
public PrintStream(java.io.InputStream is) {
__is = is;
}
@Override
public void run() {
try {
while (this != null) {
int _ch = __is.read();
if (_ch != -1)
System.out.print((char) _ch);
else
break;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// 为了在博客里好发,单独写了一个简单demo,大家根据自己的需求,整合成工具类吧
// mp4路径
String mp4Path = "D:\\test.mp4";
// ffmpeg 路径
String ffmpegPath = "D:\\ffmpeg\\bin\\ffmpeg.exe";
// m3u8输出路径
String m3u8PathPrefix = "D:\\";
try {
List<String> command = new ArrayList<String>();
command.add(ffmpegPath + "");
command.add("-i");
command.add(mp4Path);
command.add("-hls_time");
command.add("20");
command.add("-hls_list_size");
command.add("0");
command.add("-c:a");
command.add("aac");
command.add("-strict");
command.add("-2");
command.add("-f");
command.add("hls");
command.add(m3u8PathPrefix + "test.m3u8");
Process videoProcess = new ProcessBuilder(command).redirectErrorStream(true).start();
new PrintStream(videoProcess.getInputStream()).start();
videoProcess.waitFor();
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
ffmpeg还是很强大的,主要用来做音视频处理,用法还有很多。代码里写的ffmpeg命令只是一个基础的mp4转化为m3u8的命令。大家也可以按照自己的研究来进行替换,有很多参数可以设置,具体的参数去ffmpeg官网学习了解下。
貌似官网下载ffmpeg的包比较慢,我就在资源里放了一份,大家可以自行下载。ffmpeg win64包
参考链接: