using Microsoft.AspNetCore.Mvc;
namespace AA
{
public class VideoTranscoding
{
/// <summary>
/// 上传分片文件
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
public static async Task<object> UploadFiles([FromForm] IFormCollection collection)
{
//FormFileCollection filelist = (FormFileCollection)collection.Files;
//var data = filelist["data"];
//string lastModified = Request.Form["lastModified"].ToString();
//var total = Request.Form["totalPage"];
//var fileName = Request.Form["fileName"];
//var index = Request.Form["page"];
//var Vname = Request.Form["SName"];
//var fileExt = "." + Request.Form["fileExt"];
$"{Directory.GetCurrentDirectory()}/wwwroot/"
//string temporary = Path.Combine($"{Directory.GetCurrentDirectory()}/wwwroot/", lastModified);//临时保存分块的目录
//try
//{
// if (!Directory.Exists(temporary))
// Directory.CreateDirectory(temporary);
// string filePath = Path.Combine(temporary, index.ToString());
// if (!Convert.IsDBNull(data))
// {
// await Task.Run(() => {
// FileStream fs = new FileStream(filePath, FileMode.Create);
// data.CopyTo(fs);
// fs.Close();
// });
// }
// object mergeOk = false;
// //string Time = DateTime.Now.ToString("yyMMddHHmmss");
// string Time = Vname;
// Dictionary<string, object> result = new Dictionary<string, object>();
// if (total == index)
// {
// mergeOk = await FileMerge(lastModified, fileExt, Time);
// result.Add("number", index);
// result.Add("mergeOk", mergeOk);
// result.Add("VideoId", Time);
// result.Add("status", 2);
// }
// else
// {
// result.Add("number", index);
// result.Add("mergeOk", mergeOk);
// result.Add("VideoId", Time);
// result.Add("status", 1);
// }
// if ((bool)mergeOk)
// {
// // string fileExt = Path.GetExtension(fileName);//获取文件后缀
// DirectoryInfo di = new DirectoryInfo($"{Directory.GetCurrentDirectory()}/wwwroot/" + Time + "/");
// if (!di.Exists)
// {
// di.Create();
// }
// di = new DirectoryInfo(@"C:\Users\Administrator\Desktop\dist\media\" + Time + @"\");
// if (!di.Exists)
// {
// di.Create();
// }
// //$"{Directory.GetCurrentDirectory()}/wwwroot/" + Time + "/"
// Convert2Flv($"{Directory.GetCurrentDirectory()}/wwwroot/" + Time + "/" + Time + "" + fileExt, @"C:\Users\Administrator\Desktop\dist\media\" + Time + @"\");
// System.IO.File.Delete($"{Directory.GetCurrentDirectory()}/wwwroot/" + Time + "/" + Time + "" + fileExt);//删除文件
// Directory.Delete($"{Directory.GetCurrentDirectory()}/wwwroot/" + Time);//删除文件夹
// }
return "";
//}
//catch (Exception ex)
//{
// Directory.Delete(temporary);//删除文件夹
// throw ex;
//}
}
/// <summary>
/// 分片文件进行合并
/// </summary>
/// <param name="lastModified"></param>
/// <param name="fileExts"></param>
/// <param name="NewfileName"></param>
/// <returns></returns>
public static async Task<object> FileMerge(string lastModified, string fileExts, string NewfileName)
{
string erro = "";
bool ok = false;
try
{
var temporary = Path.Combine($"{Directory.GetCurrentDirectory()}/wwwroot/", lastModified);//临时文件夹
//fileName = Request.Form["fileName"];//文件名
string fileExt = fileExts;//获取文件后缀
var files = Directory.GetFiles(temporary);//获得下面的所有文件
DirectoryInfo di = new DirectoryInfo($"{Directory.GetCurrentDirectory()}/wwwroot/" + NewfileName + "/");
if (!di.Exists)
{
di.Create();
}
var finalPath = Path.Combine($"{Directory.GetCurrentDirectory()}/wwwroot/" + NewfileName + "/", NewfileName + fileExt);//最终的文件名(demo中保存的是它上传时候的文件名,实际操作肯定不能这样)
var fs = new FileStream(finalPath, FileMode.Create);
foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序,保证从0-N Write
{
var bytes = System.IO.File.ReadAllBytes(part);
await fs.WriteAsync(bytes, 0, bytes.Length);
bytes = null;
System.IO.File.Delete(part);//删除分块
}
fs.Close();
Directory.Delete(temporary);//删除文件夹
ok = true;
}
catch (Exception ex)
{
erro = ex.Message;
}
return ok;
}
/// <summary>
/// 转成m3u8格式
/// </summary>
/// <param name="vFileName"></param>
/// <param name="ExportName"></param>
/// <param name="ffmpegPath"></param>
/// <returns></returns>
public static bool Convert2Flv(string vFileName, string ExportName, string ffmpegPath)
{
try
{
string Command = @" -i " + vFileName + " -profile:v baseline -level 3.0 -start_number 0 -hls_time 10 -hls_list_size 0 -f hls " + ExportName + "ylky.m3u8"; //m3u8格式
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = ffmpegPath;
p.StartInfo.Arguments = Command;
p.StartInfo.WorkingDirectory = $"{Environment.CurrentDirectory}";
#region cmd执行
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.Start();//启动线程
p.WaitForExit();//等待完成
p.Close();//关闭进程
p.Dispose();//释放资源
// convertVideoImage(vFileName, ExportName,ffmpegPath);
#endregion
}
catch (Exception e)
{
throw e;
}
return true;
}
/// <summary>
/// 截取视频图片作为封面
/// </summary>
/// <param name="VideoPath"></param>
/// <param name="savaRd"></param>
/// <param name="ffmpegPath"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static string convertVideoImage(string VideoPath = "", string savaRd = "", string ffmpegPath = "")
{
string str_MyProg = $"{Environment.CurrentDirectory}";
if (string.IsNullOrEmpty(VideoPath))
{
return string.Empty;
}
string str_CommandArgs = "";
var file1 = new FileInfo(VideoPath);
if (file1.Exists)
{
try
{
//string save_folder = file1.FullName.Replace(file1.Name, "");
string image_file = file1.Name.Replace(file1.Extension, ".jpg");
string save_folder = savaRd;
//#设置参数以直接输出图像序列(帧),第3秒
str_CommandArgs = "-i " + VideoPath + " -ss 00:00:03 -vframes 1 -an -y -f mjpeg " + save_folder + image_file;
System.Diagnostics.ProcessStartInfo cmd_StartInfo = new System.Diagnostics.ProcessStartInfo();
cmd_StartInfo.FileName = @"D:\ffmpeg-6.0-essentials_build\bin\ffmpeg.exe";
cmd_StartInfo.Arguments = str_CommandArgs;
cmd_StartInfo.WorkingDirectory = $"{Environment.CurrentDirectory}";
cmd_StartInfo.RedirectStandardError = false; //set false
cmd_StartInfo.RedirectStandardOutput = false; //set false
cmd_StartInfo.UseShellExecute = true; //set true
cmd_StartInfo.CreateNoWindow = true; //don't need the black window
//创建一个进程,分配它的ProcessStartInfo并启动它
System.Diagnostics.Process cmd = new System.Diagnostics.Process();
cmd.StartInfo = cmd_StartInfo;
cmd.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
cmd.Start();
//System.Threading.Thread.Sleep(1000);
cmd.WaitForExit();//等待完成
cmd.Close();
cmd.Dispose();
return image_file;
}
catch (Exception ee)
{
throw new Exception(ee.StackTrace + ee.Message + " for: " + str_MyProg + " " + str_CommandArgs);
}
}
else
{
throw new Exception("No exists file:" + VideoPath);
}
}
}
}