• ASP.NET Mvc+FFmpeg+Video实现视频转码


    目录

    首先,做了视频上传的页面:

     FFmpeg:视频转码

    FFmpegHelper工作类:

    后台控制器代码: 

    前端视图代码:

     参考文章:


    首先,做了视频上传的页面:

    借鉴了这篇文章

    ASP.NET MVC+LayUI视频上传 - 追逐时光者 - 博客园 (cnblogs.com)

    其中的(maxRequestLength和maxAllowedContentLength)设置我是这样设置的

    1. "true" targetFramework="4.6.2" />
    2. "4.6.2" maxRequestLength="2147483647" executionTimeout="600" />
    3. "2147483647"/>

    layUI相关的报引用的是最新版的:发现最新版的只需要引用layui不需要layer

    2.后续发现Video标签只支持以下几种格式就涉及到视频转码了:

    格式IEFirefoxOperaChromeSafari
    OggNo3.5+10.5+5.0+No
    MPEG 49.0+NoNo5.0+3.0+
    WebMNo4.0+10.6+6.0+No

     FFmpeg:视频转码

    第一步首先在网上下载ffmpeg.exe程序,并保存到工程目录中

    ffmpeg安装教程(windows版)_ffmpeg windows安装-CSDN博客

    FFmpegHelper工作类:

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Diagnostics;
    4. using System.Linq;
    5. using System.Web;
    6. namespace Player.Helper
    7. {
    8. public class FFmpegHelper
    9. {
    10. //安装的ffmpeg的路径 写在配置文件的 你也可以直接写你的路径 D:\ffmpeg\bin\ffmpeg.exe
    11. //static string FFmpegPath = System.Configuration.ConfigurationManager.AppSettings["ffmepg"];
    12. ///
    13. /// 视频转码为mp4文件
    14. ///
    15. ///
    16. ///
    17. public static void VideoToTs(string videoUrl, string targetUrl)
    18. {
    19. //视频转码指令
    20. string cmd = string.Format("ffmpeg -i \"{0}\" -y -ab 32 -ar 22050 -b 800000 -s 480*360 \"{1}\"", videoUrl, targetUrl);
    21. RunMyProcess(cmd);
    22. }
    23. ///
    24. /// 执行cmd指令
    25. ///
    26. ///
    27. public static void RunMyProcess(string Parameters)
    28. {
    29. using (Process p = new Process())
    30. {
    31. try
    32. {
    33. p.StartInfo.FileName = "cmd.exe";
    34. p.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动
    35. p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
    36. p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
    37. p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
    38. p.StartInfo.CreateNoWindow = false;//不创建进程窗口
    39. p.Start();//启动线程
    40. p.StandardInput.WriteLine(Parameters + "&&exit"); //向cmd窗口发送输入信息
    41. p.StandardInput.AutoFlush = true;
    42. p.StandardInput.Close();
    43. //获取cmd窗口的输出信息
    44. string output = p.StandardError.ReadToEnd(); //可以输出output查看具体报错原因
    45. p.WaitForExit();//等待完成
    46. p.Close();//关闭进程
    47. p.Dispose();//释放资源
    48. }
    49. catch (Exception ex)
    50. {
    51. throw ex;
    52. }
    53. }
    54. }
    55. }
    56. }

    后台控制器代码: 

    1. using Player.Helper;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.IO;
    5. using System.Linq;
    6. using System.Text;
    7. using System.Web;
    8. using System.Web.Mvc;
    9. using static System.Net.WebRequestMethods;
    10. namespace Player.Controllers
    11. {
    12. public class FileUploadController : Controller
    13. {
    14. // GET: FileUpload
    15. public ActionResult Index()
    16. {
    17. return View();
    18. }
    19. ///
    20. /// 对验证和处理 HTML 窗体中的输入数据所需的信息进行封装,如FromData拼接而成的文件[图片,视频,文档等文件上传]
    21. ///
    22. /// FemContext对验证和处理html窗体中输入的数据进行封装
    23. ///
    24. [AcceptVerbs(HttpVerbs.Post)]
    25. public ActionResult FileLoad(FormContext context)//FemContext对验证和处理html窗体中输入的数据进行封装
    26. {
    27. HttpPostedFileBase httpPostedFileBase = Request.Files[0];//获取文件流
    28. if (httpPostedFileBase != null)
    29. {
    30. try
    31. {
    32. ControllerContext.HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8");
    33. ControllerContext.HttpContext.Response.Charset = "UTF-8";
    34. string fileName = Path.GetFileName(httpPostedFileBase.FileName);//原始文件名称
    35. string fileExtension = Path.GetExtension(fileName);//文件扩展名
    36. byte[] fileData = ReadFileBytes(httpPostedFileBase);//文件流转化为二进制字节
    37. string result = SaveFile(fileExtension, fileData);//文件保存
    38. return string.IsNullOrEmpty(result) ? Json(new { code = 0, path = "", msg = "网络异常,文件上传失败.~" }) : Json(new { code = 1, path = result, msg = "文件上传成功" });
    39. }
    40. catch (Exception ex)
    41. {
    42. return Json(new { code = 0, msg = ex.Message, path = "" });
    43. }
    44. }
    45. else
    46. {
    47. return Json(new { code = 0, path = "", msg = "网络异常,文件上传失败!~" });
    48. }
    49. }
    50. ///
    51. /// 将文件流转化为二进制字节
    52. ///
    53. /// 图片文件流
    54. ///
    55. private byte[] ReadFileBytes(HttpPostedFileBase fileData)
    56. {
    57. byte[] data;
    58. using (var inputStream = fileData.InputStream)
    59. {
    60. if (!(inputStream is MemoryStream memoryStream))
    61. {
    62. memoryStream = new MemoryStream();
    63. inputStream.CopyTo(memoryStream);
    64. }
    65. data = memoryStream.ToArray();
    66. }
    67. return data;
    68. }
    69. ///
    70. /// 保存文件
    71. ///
    72. /// 文件扩展名
    73. /// 图片二进制文件信息
    74. ///
    75. private string SaveFile(string fileExtension, byte[] fileData)
    76. {
    77. string result;
    78. string saveName = Guid.NewGuid().ToString() + fileExtension; //保存文件名称
    79. string basePath = "UploadFile";
    80. string saveDir = DateTime.Now.ToString("yyyy-MM-dd");
    81. // 文件上传后的保存路径
    82. string serverDir = Path.Combine(Server.MapPath("~/"), basePath, saveDir);
    83. string fileNme = Path.Combine(serverDir, saveName);//保存文件完整路径
    84. try
    85. {
    86. var savePath = Path.Combine(saveDir, saveName);
    87. //项目中是否存在文件夹,不存在创建
    88. if (!Directory.Exists(serverDir))
    89. {
    90. Directory.CreateDirectory(serverDir);
    91. }
    92. System.IO.File.WriteAllBytes(fileNme, fileData);//WriteAllBytes创建一个新的文件,按照对应的文件流写入,假如已存在则覆盖
    93. //返回前端项目文件地址
    94. result = "/" + basePath + "/" + saveDir + "/" + saveName;
    95. //进行视频转换
    96. var mp4Name = Guid.NewGuid().ToString() + ".mp4";
    97. string tsUrl = Path.Combine(serverDir, mp4Name);
    98. FFmpegHelper.VideoToTs(fileNme, tsUrl);
    99. //检测是否已生成ts文件
    100. if (!System.IO.File.Exists(tsUrl))
    101. {
    102. //删除源文件
    103. System.IO.File.Delete(fileNme);
    104. return null;
    105. }
    106. //删除MP4源文件
    107. System.IO.File.Delete(fileNme);
    108. result = "/" + basePath + "/" + saveDir + "/" + mp4Name;
    109. }
    110. catch (Exception ex)
    111. {
    112. result = "发生错误" + ex.Message;
    113. }
    114. return result;
    115. }
    116. }
    117. }

    前端视图代码:

    1. "utf-8" />
    2. "X-UA-Compatible" content="IE=edge,chrome=1">
    3. "~/Content/Layui/css/layui.css" rel="stylesheet" />
    4. class="jumbotron" style="margin-top: 200px;">
    5. class="row" style="margin-top: 20px;">
    6. class="form-group znStyle">
    7. class="col-sm-6">
    8. "upload_all_file">
    9. class="layui-upload">
    10. "hidden" name="Video" id="Video" />
    11. class="layui-upload-list" id="videoPlay">
  •  参考文章:

    Request Limits | Microsoft Learn

    httpRuntime代码放在web.config哪里?深度了解httpRuntime - ASP.NET编程_卡卡网

  • 相关阅读:
    令人头痛的延时双删
    零代码编程:用ChatGPT将特定文件标题重命名为特定格式
    torch.autograd
    端到端测试(End-to-end tests)重试策略
    IDEA 快捷键
    教你一招,测试人员如何通过AI提高工作效率!
    采集数据重复解决方法
    Sui的动态可组合NFT为Cosmocadia增加游戏趣味性
    JAVA 文件上传 和 下载
    Labview CIE ColorTool Lib (源码vi)
  • 原文地址:https://blog.csdn.net/qq_60521457/article/details/136650441