我用java調用mencoder實施轉碼,但是轉碼過程中出現子進程阻塞,而且還是看了API才知道這個問題的。因為mencoder的控制台輸出資訊很多,把緩衝區所有的空間佔滿了,所以程式不能執行後面的程式,mencoder就只能轉碼28秒的視頻,所以需要建立線程及時清空緩衝區。
建立一個類StreamGobble類:
package thss.jmencoder;<br />import java.io.BufferedReader;<br />import java.io.IOException;<br />import java.io.InputStream;<br />import java.io.InputStreamReader;<br />public class StreamGobble extends Thread {<br /> InputStream is;<br /> String type; </p><p> StreamGobble(InputStream is, String type) {<br /> this.is = is;<br /> this.type = type;<br /> } </p><p> public void run() {<br /> try {<br /> InputStreamReader isr = new InputStreamReader(is);<br /> BufferedReader br = new BufferedReader(isr);<br /> String line = null;<br /> while ((line = br.readLine()) != null)<br /> System.out.println(type + ">" + line);<br /> } catch (IOException ioe) {<br /> ioe.printStackTrace();<br /> }<br /> }<br />} </p><p>
在main函數中調用Runtime/Process執行轉碼
String line = value.toString();<br />String[] str = line.split(" ");<br />String fOutput = null;<br />fOutput = str[3] + ".flv";<br />Process process = null;<br />try {<br /> Runtime runtime = Runtime.getRuntime();<br /> process = runtime .exec("mencoder -ofps 30000/1001 -vf harddup"<br /> + " /user/student/data/"+str[0]<br /> + " -ss "+str[1]+" -endpos "+str[2]+" -sws 2 -of lavf -ovc lavc -lavcopts "<br /> + "vcodec=flv:vbitrate=500:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 "<br /> + "-nosound -srate 22050 -o /user/student/data/"+fOutput);<br /> new StreamGobble(process.getInputStream(), "INFO").start();<br /> new StreamGobble(process.getErrorStream(), "ERROR").start();<br /> int status = process.waitFor();<br /> System.out.println("Process exitValue: " + status);<br /> } catch (Throwable t) {<br /> t.getStackTrace();<br /> } finally {<br /> if (process == null)<br /> process.destroy();<br /> process = null;<br /> }<br />