在C#程序中,使用ffmpeg.exe可對音頻文件進行格式轉換和轉碼。下面的代碼可將amr格式的音頻文件轉爲ogg格式的音頻文件,inputPath 爲輸入文件路徑,outputPath爲輸出文件路徑。
“-acodec libvorbis”指定轉碼使用的庫,“-ar 44100 -ac 2”指定轉碼後的音頻文件參數,其中“-ac 2”指定雙聲道。“-acodec libvorbis -ar 44100 -ac 2”這段指令在某些格式之間轉換時可省略,例如ogg轉爲mp3時,直接使用“ExecuteCommand(pc,"\""+ ffmpegPath + "\"" + " -i " + "\""+ inputPath + "\"" + " " + "\""+ outputPath + "\"", out output, outerror);”即可。ExecuteCommand函數請參考之前的文章《FFmpeg C#應用(一):執行指令》。
public bool VoiceTransfer(string inputPath,stringoutputPath)
{
if(System.IO.File.Exists(inputPath))
{
if(System.IO.File.Exists(outputPath))
{
File.Delete(outputPath);
}
stringffmpegPath =new FileInfo(Process.GetCurrentProcess().MainModule.FileName).DirectoryName+@"\ffmpeg.exe";
stringoutput = string.Empty;
stringerror = string.Empty;
Processpc = new Process();
ExecuteCommand(pc, "\"" + ffmpegPath +"\"" + "-i " +"\"" +inputPath + "\"" + " -acodec libvorbis -ar 44100 -ac 2 " +"\"" + outputPath + "\"", outoutput, out error);
Regex regex = new Regex("(\\d{2,4})x(\\d{2,4})",RegexOptions.Compiled);
if(!string.IsNullOrEmpty(error))
{
Matchm = regex.Match(error);
if(m != null)
{
if (!m.Success)
{
File.Delete(inputPath);
returntrue;
}
}
}
}
returnfalse;
}
資料
FFmpeg官網: http://www.ffmpeg.org
FFmpeg doc : http://www.ffmpeg.org/documentation.html
FFmpeg wiki : https://trac.ffmpeg.org/wiki