2011-09-04 66 views
5

我試圖創建使用ffmepg媒體文件轉換一個.NET包裝,這裏是我已經試過:從.NET程序與ffmpeg交互?

static void Main(string[] args) 
{ 
    if (File.Exists("sample.mp3")) File.Delete("sample.mp3"); 

    string result; 

    using (Process p = new Process()) 
    { 
    p.StartInfo.FileName = "ffmpeg"; 
    p.StartInfo.Arguments = "-i sample.wma sample.mp3"; 

    p.StartInfo.UseShellExecute = false; 
    p.StartInfo.RedirectStandardOutput = true; 

    p.Start(); 

    //result is assigned with an empty string! 
    result = p.StandardOutput.ReadToEnd(); 

    p.WaitForExit(); 
    } 
} 

實際發生的是ffmpeg的節目的內容是打印出來的控制檯應用程序,但result變量是一個空字符串。我想以交互方式控制轉換進度,因此用戶甚至不需要知道我正在使用ffmpeg,但他仍然知道轉換進度的細節以及應用程序達到的百分比等。

基本上,我也會很滿意P/Invoke轉換函數的.NET包裝器(我對整個外部庫不感興趣,除非我可以從中提取PI函數)。

任何有經驗的人ffmpeg & .NET?

更新 請查看我的另一個問題,how to write input to a running ffmpeg process

回答

4

下面是答案:

static void Main() 
{ 
    ExecuteAsync(); 
    Console.WriteLine("Executing Async"); 
    Console.Read(); 
} 

static Process process = null; 
static void ExecuteAsync() 
{ 
    if (File.Exists("sample.mp3")) 
    try 
    { 
     File.Delete("sample.mp3"); 
    } 
    catch 
    { 
     return; 
    } 

    try 
    { 
    process = new Process(); 
    ProcessStartInfo info = new ProcessStartInfo("ffmpeg.exe", 
     "-i sample.wma sample.mp3"); 

    info.CreateNoWindow = false; 
    info.UseShellExecute = false; 
    info.RedirectStandardError = true; 
    info.RedirectStandardOutput = true; 

    process.StartInfo = info; 

    process.EnableRaisingEvents = true; 
    process.ErrorDataReceived += 
     new DataReceivedEventHandler(process_ErrorDataReceived); 
    process.OutputDataReceived += 
     new DataReceivedEventHandler(process_OutputDataReceived); 
    process.Exited += new EventHandler(process_Exited); 

    process.Start(); 

    process.BeginOutputReadLine(); 
    process.BeginErrorReadLine(); 
    } 
    catch 
    { 
    if (process != null) process.Dispose(); 
    } 
} 

static int lineCount = 0; 
static void process_ErrorDataReceived(object sender, DataReceivedEventArgs e) 
{ 
    Console.WriteLine("Input line: {0} ({1:m:s:fff})", lineCount++, 
     DateTime.Now); 
    Console.WriteLine(e.Data); 
    Console.WriteLine(); 
} 

static void process_OutputDataReceived(object sender, DataReceivedEventArgs e) 
{ 
    Console.WriteLine("Output Data Received."); 
} 

static void process_Exited(object sender, EventArgs e) 
{ 
    process.Dispose(); 
    Console.WriteLine("Bye bye!"); 
} 
+0

沒有使用StringBuilder sb。 –

+0

@aaaa bbbb:刪除,謝謝。它仍然從以前的嘗試,無論如何,我添加了一些重要的功能,我的答案。 **你能否看看[這](http://stackoverflow.com/questions/7296901)**? – Shimmy

0

嘗試使用ffmpeg-sharp

+0

我不想使用其他外部工具。我很想聽聽如何爲轉換支持創建一些基本簡單的P/Invokes。有沒有辦法像我的例子那樣使用後臺進程來執行這樣的程序?我錯過了什麼? – Shimmy

+0

退房http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/ea8b0fd5-a660-46f9-9dcb-d525cc22dcbd你可以隱藏窗口,但我相信你可以讀取輸出它仍然。 –

+0

http://stackoverflow.com/questions/7296901 – Shimmy