c# 使用ffmpeg 计算音频时长 并对音频格式进行转换
1.计算音频的时长
/// <summary>
/// 计算音频的时间 单位:秒
/// </summary>
/// <param name="FileName"></param>
/// <returns></returns>
private static double VideoTime(string FileName)
{
// ffmpeg 的路径
string ffmpegPath = @"G:\FFmpegSpace\ffmpeg-master-latest-win64-gpl\bin\ffmpeg.exe";
// 构建 FFmpeg 命令
string command = $"-i \"{FileName}\"";
// 创建进程并执行 FFmpeg 命令
Process process = new Process();
process.StartInfo.FileName = ffmpegPath;
process.StartInfo.Arguments = command;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
// 读取 FFmpeg 输出信息
string output = process.StandardError.ReadToEnd();
process.WaitForExit();
// 解析输出信息以获取时长
string durationMarker = "Duration: ";
int durationIndex = output.IndexOf(durationMarker) + durationMarker.Length;
int durationLength = output.IndexOf(",", durationIndex) - durationIndex;
string durationString = output.Substring(durationIndex, durationLength);
TimeSpan duration = TimeSpan.Parse(durationString);
double minutes = duration.TotalSeconds;
// 打印音频时长
Console.WriteLine($"本次上传的音频时长为: {minutes}" + "秒");
return minutes;
}
2.对音频进行格式转换
/// <summary>
/// 把非wav格式的转换成wav 并且确保采样率为16K
/// </summary>
/// <param name="inputFilePath"></param>
/// <param name="outputFilePath"></param>
/// <returns></returns>
private static string WavChangeType(string inputFilePath, string outputFilePath)
{
try
{
// FFmpeg 可执行文件路径 需要替换自己电脑上的路径
string ffmpegPath = @"G:\FFmpegSpace\ffmpeg-master-latest-win64-gpl\bin\ffmpeg.exe";
// 构建 FFmpeg 命令 并且确保采样率为16K
string command = $"-i \"{inputFilePath}\" -ar 16000 \"{outputFilePath}\"";
// 创建进程并执行 FFmpeg 命令
Process process = new Process();
process.StartInfo.FileName = ffmpegPath;
process.StartInfo.Arguments = command;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
string output = process.StandardError.ReadToEnd();
process.WaitForExit();
try
{
if (process.ExitCode == 0)
{
Console.WriteLine("音频成功转换为wav格式!!!");
}
else
{
Console.WriteLine("音频类型转换失败" + output);
}
}
catch (Exception e)
{
Console.WriteLine("音频类型转换失败" + e.Message);
}
}
catch (Exception e)
{
Console.WriteLine("音频类型转换失败" + e.Message);
}
//G:\appaa\ConsoleApp6\bin\Debug\net6.0\20231027113519.wav
var filePath = outputFilePath;
return filePath;
}