目的:读取远程 rtsp的数据保存到本地,生成一个mp4文件。
ffmpeg下载地址:/builds/
ffmpeg工具:ffmpeg4.0.2,位于解压后的bin/
直接上代码:
import ;
import ;
import ;
import ;
public class TestWinFFRtsp implements Runnable{
InputStream in ; // 正常输出流
boolean stop ; // 结束进程
int maxFrameCount = 2000;
Process pro ;
public TestWinFFRtsp(Process process, InputStream in ){
= in;
= process;
}
public void setStop(boolean stop) {
= stop;
}
public static void main(String[] args) throws Exception{
("###使用进程的方式进行编码###");
// 1. 视频转换视频
String rtspUrl = "rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov";
String dest = "E:/tmp/201810/testff/bbb3.mp4";
convert(rtspUrl, dest);
("###end###");
}
public static void convert(String src,String dest)throws Exception{
String ffcmdpath = "F:\\lee\\apps\\ffmpeg20181005\\bin\\";
StringBuilder cmd = new StringBuilder();
(ffcmdpath)
.append(" -rtsp_transport tcp ") // 使用tcp的命令,默认是udp
.append(" -i ").append(src)
// .append(" -vcodec copy ")
.append(" -vcodec h264 ")
// .append(" -acodec copy ") // 音频,不设置好像也有。
// .append(" -s 1280*720 ") // 设置分辨率,关系到视频的大小或者为 -vf scale=iw/2:ih/2
// .append(" -vf scale=iw/2:ih/2 ")
.append(" -y ") // 覆盖
.append(dest);
("cmd="+());
("###start cmd="+new Date().toLocaleString());
Process process = ().exec(());
// 输出内容
TestWinFFRtsp twffIn = new TestWinFFRtsp(process, ());
TestWinFFRtsp twffInErr = new TestWinFFRtsp(process,());
Thread t = new Thread(twffIn);
Thread t1 = new Thread(twffInErr);
();();
// 停止指令,10秒后停止 ,一定要发送这个,要不然视频保存不下来
//
int i = (); // 一定要配合2个 inputstream ,要不然会一直阻塞
(i+"###end cmd="+new Date().toLocaleString());
(true);(true); // 停止 线程
}
/**
* @title stopConvert
* @date 2018年10月11日
* @param process
* @return
* @description 发送停止命令,
* 但是要注意发送完成后,不一定会马上停止 。因为进程结束也是需要时间的
*/
public static boolean stopConvert(Process process ){
("###send q cmd ");
try{
OutputStream os = ();
("q".getBytes());
(); // 一定要
}catch(Exception err){
();
return false;
}
return true;
}
@Override
public void run() {
Scanner scanner = new Scanner(in);
while(!stop){
if(()){
String s = ();
(s);
// 判断停止录像的条件
if(("frame=") && ("fps=") > 6){
String frameCountStr = (6
,("fps="));
// (("fps=") + ",frameCountStr="+frameCountStr);
// 获得当前解析到的帧数,退出
int frameCount = (());
if(frameCount > maxFrameCount){
("##maxFrameCount="+maxFrameCount +",frameCount="+frameCount);
stopConvert(pro);
}
}
}else{
try {
(500);
} catch (InterruptedException e) {
();
}
}
}
();
("###读取线程结束啦###");
}
}