C# ffmpeg 視頻處理格式轉換和添加水印


通過C#調用ffmpeg 將flv格式轉換為mp4格式,並添加水印

C#調用ffmpeg的方法封裝如下:


/// <summary>
/// 視頻處理器ffmpeg.exe的位置
/// </summary>
public string FFmpegPath { get; set; }

/// <summary>
/// 調用ffmpeg.exe 執行命令
/// </summary>
/// <param name="Parameters">命令參數</param>
/// <returns>返回執行結果</returns>
private string RunProcess(string Parameters)
{
//創建一個ProcessStartInfo對象 並設置相關屬性
var oInfo = new ProcessStartInfo(FFmpegPath, Parameters);
oInfo.UseShellExecute = false;
oInfo.CreateNoWindow = true;
oInfo.RedirectStandardOutput = true;
oInfo.RedirectStandardError = true;
oInfo.RedirectStandardInput = true;

//創建一個字符串和StreamReader 用來獲取處理結果
string output = null;
StreamReader srOutput = null;

try
{
//調用ffmpeg開始處理命令
var proc = Process.Start(oInfo);

proc.WaitForExit();


//獲取輸出流
srOutput = proc.StandardError;

//轉換成string
output = srOutput.ReadToEnd();

//關閉處理程序
proc.Close();
}
catch (Exception)
{
output = string.Empty;
}
finally
{
//釋放資源
if (srOutput != null)
{
srOutput.Close();
srOutput.Dispose();
}
}
return output;
}


轉換格式的命令參數:-i orignal.flv -y -b 1024k -acodec copy -f mp4 newFile.mp4

添加水印的命令參數:-i orignal.flv -i water.png -filter_complex \"overlay=10:10\" newFile.flv

 

參數簡要說明和細節提示

orignal.flv : 要處理的原始視頻文件(最好是絕對路徑)
-y : 覆蓋已有文件(注意,加水印不可覆蓋原始文件,否則只能生成1秒的視頻)
-b:視頻的碼率 這里設置1024k 基本可滿足無損處理 如不設置-b參數則默認為200k 視頻會非常模糊
-acodec copy : 保持音頻質量不變
-f mp4 : 表示轉換的視頻格式
 
-i water.png : 水印圖片路徑
overlay=10:10 : 水印距離視頻的左上角坐標
其他位置參數:
右上角:main_w-overlay_w-10:10
左下角:10:main_h-overlay_h-10
右下角:main_w-overlay_w-10:main_h-overlay_h-10
 
newFile.mp4  要保存的文件路徑

 

筆者嘗試了各種命令的組合,發現對於不同版本的ffmpeg,有的參數是不能使用的,就筆者使用的2.8.2版本最終 找了一個比較好的解決方案:

可以選擇使用以下命令參數:

//同時轉換格式和加水印

-i orignal.flv -i water.png -filter_complex \"overlay=10:10\" -y -b 1024k -acodec copy -f mp4

 //只加水印,不做格式轉換

-i orignal.flv -i water.png -filter_complex \"overlay=10:10\" -b 1024k -acodec copy

 

 

總結:                                                          
C#調用ffmpeg時 不要使用proc.WaitForExit();方法,否則會假死

ffmpeg的版本最好使用最新版本,並參考命令參數說明

無損轉換,無損加水印 要注意保證視頻的碼率 和音頻的參數(直接copy,視頻不能這樣寫-avcodec copy  會報錯,只能用-b設置視頻碼率) 

 

原文鏈接:https://blog.csdn.net/zhongjie112/article/details/50448327


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM