最近工做中須要常常使用ffmpeg
一類的命令行程序,爲了不過多重複操做,因而思考了下編寫命令程序腳本的幾種方式,包括c#,python,bat,powershell,shell。html
C#
/// <summary> /// 使用 process 調用程序 /// 對指定視頻轉碼 /// </summary> private static void Ffmpeg() { using (var p = new Process()) { // 想要運行命令/程序名/程序絕對路徑 // ffmpeg 已添加至 path p.StartInfo.FileName = @"ffmpeg"; p.StartInfo.Arguments = "-i 1.mp4 -c:v libx264 -c:a aac -y 1.flv"; // true 就沒法重定向輸出或報錯 // http://stackoverflow.com/questions/5255086/when-do-we-need-to-set-useshellexecute-to-true p.StartInfo.UseShellExecute = false; // ffmpeg 比較特殊,全部信息都從Error出 p.StartInfo.RedirectStandardError = true; //p.StartInfo.RedirectStandardOutput = true; p.Start(); using (var reader = p.StandardError) { while (!reader.EndOfStream) Console.WriteLine(reader.ReadLine()); } // 等待進程 p.WaitForExit(); } }
fabric
這個強大的工具,官方實現是使用python2,不過可以使用pip install fabric3
下載它的python3實現。(python3 下使用pip install fabric 也會正常下載,不過沒法使用)fabfile
,否者要使用-f file
加載fabfile.py:python
from fabric.api import local import json def flv(): """ 獲取視頻長度 """ data = local('ffprobe -v quiet -print_format json -show_format -show_streams {0}'.format('1.flv'), capture=True) info = json.loads(data.stdout) print(info['format']['duration'])
fab flvlinux
批處理能夠在win中快速編寫簡單命令腳本shell
REM @echo off REM 批量切割視頻 for %%c in (*.mp4) do ( ffmpeg -i %%c -ss 1 -t 1 -v quiet -y %%~nc.flv )
bash
的shell程序,它提供了比批處理更強大的能力,而且如今已開源,微軟也提供了官方的跨平臺實現xx.ps1
腳本,可能會報權限錯誤,在管理員權限的powershell
中執行set-ExecutionPolicy RemoteSigned
便可,參照張善友大神的博文powershell的功能很是強大,同時也具備面向對象思惟json
# 獲取當前目錄全部flv時長 function FlvInfo ($video) { $pattern = ".*?(?<Size>\d+).*?" $line = ffprobe -v quiet -print_format json -show_format $video | Where-Object {$_ -like '*size*'} $result = $line -match $pattern $size = $Matches.Size Write-Output "$video size: $size" } foreach ($item in Get-ChildItem -Filter "*.flv*") { FlvInfo $item.Name }
shell 是linux下的神兵利器,得益於WSL
,咱們在Win10下也能自由的使用Shell來完成平常操做c#
#!/bin/bash for video in `ls |grep mp4` do ffmpeg -i $video -c:v copy -c:a copy -y ${video:0:-4}.flv done
使用c#,python等方式調用命令行程序能夠簡化批量處理大量重複、複雜和流程化的操做,而批處理,powershell,shell也能夠快速簡單地減小命令使用,總的來講要根據具體場景選擇襲擊喜歡的方式吧。api