天天看點

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;
	}