最近工做中须要常常使用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