Java 使用FFmpeg进行音视频文件合并

FFmpeg实现音视频文件合并

 

最近需要用到将得到的音视频文件进行合并,查找资料发现FFmpeg是个非常不错的开源软件。简单几条命令行就能实现大用途。现将自己写的代码贴出来,以免再次翻找资料浪费时间。

 

我是做Java的,属刚入门,希望大家多批评指正,共同进步,谢谢。

 

关于FFmpeg的命令行,可以查看我的另一篇文档:http://zk461759809.iteye.com/admin/blogs/1636634

 

public boolean mergeFile(File file) {

		//合并文件
		//头一个file为amr文件
		try {
			log.info("Begin to merge video file " + videoFile.getAbsolutePath() + " into " + armFile.getAbsolutePath());
			

			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
			if(classLoader == null) {
				classLoader = ClassLoader.getSystemClassLoader();
			}
			//注意FFmpeg路径




			String command =new File(classLoader.getResource("").toURI()).getParentFile() + "\\ffmpeg -i " + armFile.getAbsolutePath() + " -r 15 -i " 
			+ videoFile.getAbsolutePath() + " -vf \"transpose=1\" -c:a copy -c:v libx264 " + videoFile.getParentFile() + "\\_" + videoFile.getName();
//			System.out.println(command);
			
			log.info("The command of ffmpeg is " + command);
			
			Process process =Runtime.getRuntime().exec(command);
			
			final InputStream in = process.getInputStream();
			final InputStream error = process.getErrorStream();
			
			//等待该进程结束后在执行后面操作




			new Thread(){
				public void run() {
					BufferedReader br = new BufferedReader(new InputStreamReader(error));
					
					try {
						while(br.readLine() != null) {
							continue;
						}
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						try {
							br.close();
							in.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
						
					}
				};
			}.start();
			
                        //waitFor()操作阻塞线程,等待process执行结束
			process.waitFor();

                        process.destroy();
			
			log.info("Success to execute " + command);
			log.info("Success to merge " + videoFile.getAbsolutePath() + " into " + armFile.getAbsolutePath() + ", and success to create " +  videoFile.getParentFile() + "/_" + videoFile.getName());
			
			
		} catch (Exception e) {
			
			log.error("Exception occurs when merging video file", e);
			return false;
		}
		
		return true;
	}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值