个人在使用中的整理
要转码这个文件需要用到外部的一个插件那就是:ffmpeg.exe
将这个插件添加到你的项目中
//获取文件的本地地址:System.AppDomain.CurrentDomain.BaseDirectory
/// <summary>
/// 将amr转为mp3的格式
pathBefore:转换之前的文件的路径
pathLater:转换之后的文件要存放的地址
/// </summary>
public static string ConvertToMp3(string pathBefore, string pathLater)
{
string changePath = MapPath("/ffmpeg/");
string AfterFileName = changePath.Replace("\\bin\\x64\\Debug\\", "\\");//去掉编译生成的文件,会对ffmpeg.exe的路径有影响
string allPath = AfterFileName + @"ffmpeg.exe -i " + pathBefore + " " + pathLater;
string str = RunCmd(allPath);
return str;
}
/// <summary>
/// 执行Cmd命令
/// </summary>
public static string RunCmd(string c)
{
try
{
string output;
using (Process p = new Process())
{
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true; //重定向标准错误输出
p.StartInfo.CreateNoWindow = true; //不显示程序窗口
p.Start();//启动程序
//向cmd窗口写入命令
p.StandardInput.WriteLine(c+ "&exit");
p.StandardInput.AutoFlush = true;
//获取cmd窗口的输出信息
output = p.StandardOutput.ReadToEnd();
p.WaitForExit();//等待程序执行完退出进程
p.Close();
}
return output;
}
catch (Exception ex)
{
return "error" + ex.Message;
}
}
注意
转码前和转码后的文件地址都是真实存在的,如,我是用vs2017 +c#实现的,但是有的文件夹是编译的过程中才生成的所以文件路径要注意,在定位ffmpeg.exe 在项目中的位置时,路径中不要出现编译的时候才会生成的文件的路径
这个方法可以完成文件的转码不过有个问题我还没有解决
问题
我是先将文件从文件服务器上面下载下来,然后一个一个进行转码,但是每次都只转成功一个问题,执行到RunCmd中的这句时,output = p.StandardOutput.ReadToEnd();就不会在继续执行后面的循环了
下面是后来找到的批量转码的方法:
string ffmpegPath = AppDomain.CurrentDomain.BaseDirectory + "cmd\\ffmpeg";
foreach (FileInfo f in fileList)
{
if (contentDic.ContainsKey(f.Name))
{
using (System.Diagnostics.Process pc = new System.Diagnostics.Process())
{
pc.StartInfo.FileName = "cmd.exe";
pc.StartInfo.CreateNoWindow = true;//隐藏窗口运行
pc.StartInfo.RedirectStandardError = true;//重定向错误流
pc.StartInfo.RedirectStandardInput = true;//重定向输入流
pc.StartInfo.RedirectStandardOutput = true;//重定向输出流
pc.StartInfo.UseShellExecute = false;
pc.Start();
pc.StandardInput.AutoFlush = true;
string cmd = $"{ffmpegPath} -i {f.FullName} {tempFold}\\{contentDic[f.Name]}";
pc.StandardInput.WriteLine(cmd);
pc.StandardInput.WriteLine("exit");
pc.WaitForExit(ffmpegSleep);//休眠一段时间,等待ffmpeg执行完(应该有更好的方案,但目前尝试过几种办法都不行)
pc.Close();
}
}
}