• html和winform webBrowser控件交互并播放视频(包含转码)


    1、 为了使网页能够与winform交互 将com的可访问性设置为真
       

    1. [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    2.     [System.Runtime.InteropServices.ComVisibleAttribute(true)]

    2、在webBrowser控件中设置可被html页面调用的类即:webBrowser1.ObjectForScripting = this;前端即可通过window.external访问this对象

    3、html页面调用后台方法:window.external.方法名(); 此处的window.external相当于webBrowser1.ObjectForScripting

    设计:

     后台代码:

    注意:视频地址需要修改

    1. using System;
    2. using System.Collections.Generic;
    3. using System.ComponentModel;
    4. using System.Data;
    5. using System.Drawing;
    6. using System.Text;
    7. using System.Linq;
    8. using System.Threading.Tasks;
    9. using System.Windows.Forms;
    10. using DevExpress.XtraEditors;
    11. using WebKit;
    12. using System.IO;
    13. using DXApplication1.Helper;
    14. namespace DXApplication1
    15. {
    16. //为了使网页能够与winform交互 将com的可访问性设置为真
    17. [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    18. [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    19. public partial class webBrowser : DevExpress.XtraEditors.XtraForm
    20. {
    21. public webBrowser()
    22. {
    23. InitializeComponent();
    24. }
    25. private void webBrowser_Load(object sender, EventArgs e)
    26. {
    27. webBrowser1.ScriptErrorsSuppressed = true;//消除脚本错误
    28. webBrowser1.Navigate(@"C:\source\repos\DXApplication1\DXApplication1\Html\HTMLPage2.html");
    29. webBrowser1.ObjectForScripting = this;
    30. }
    31. public string FileLode(string url)
    32. {
    33. //返回路径
    34. string result = url;
    35. if (!string.IsNullOrEmpty(url))
    36. {
    37. //保存文件名称
    38. string saveName = Guid.NewGuid().ToString() + ".mp4";
    39. string basePath = "UploadFile";
    40. string saveDir = DateTime.Now.ToString("yyyy-MM-dd");
    41. //获取应用程序的当前工作目录
    42. string MapPath = Directory.GetCurrentDirectory();
    43. // 文件上传后的保存路径
    44. string serverDir = Path.Combine(MapPath, basePath, saveDir);
    45. //保存文件完整路径
    46. string fileNme = Path.Combine(serverDir, saveName);
    47. //项目中是否存在文件夹,不存在创建
    48. if (!Directory.Exists(serverDir))
    49. {
    50. Directory.CreateDirectory(serverDir);
    51. }
    52. //进行视频转换
    53. FFmpegHelper.VideoToTs( url, fileNme);
    54. result = fileNme;
    55. }
    56. return result;
    57. }
    58. ///
    59. /// 前台调用后台返回数据
    60. /// 注意:前台调用的方法不能:static
    61. ///
    62. ///
    63. ///
    64. public string videoLine(int a)
    65. {
    66. var result = string.Empty;
    67. switch (a)
    68. {
    69. case 1:
    70. result = "http:/UploadFile/2024-03-12/17577f56-d999-4bbe-b67a-2156e241170d.mp4";
    71. break;
    72. case 2:
    73. result = "http:/UploadFile/2024-03-12/af67f8d3-ac79-4bd1-aa41-0743015ef9a4.m4v";
    74. break;
    75. default:
    76. result= "C:\\source\\repos\\DXApplication1\\DXApplication1\\video\\231127.m4v";
    77. break;
    78. }
    79. return result;
    80. }
    81. private void simpleButton1_Click(object sender, EventArgs e)
    82. {
    83. var url=textBox1.Text;
    84. if (!string.IsNullOrEmpty(url))
    85. {
    86. webBrowser1.ScriptErrorsSuppressed = true;
    87. webBrowser1.Navigate(url);
    88. webBrowser1.ObjectForScripting = this;
    89. }
    90. }
    91. private void simpleButton2_Click(object sender, EventArgs e)
    92. {
    93. //调用前台js方法
    94. webBrowser1.Document.InvokeScript("handinitLine", new object[] { "后台调用js方法1" });
    95. }
    96. }
    97. }

    Html代码:

    1. html>
    2. <head>
    3. <meta charset="utf-8" />
    4. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    5. <title>title>
    6. <link href="layui-v2.9.7/css/layui.css" rel="stylesheet" />
    7. head>
    8. <body>
    9. <div>
    10. <input type="file" class="layui-btn layui-btn-primary" id="videoUpload" accept="video/*">
    11. div>
    12. <div class="layui-form-item">
    13. <div class="layui-input-group">
    14. <div class="layui-input-split layui-input-prefix">
    15. div>
    16. <input type="text" placeholder="" class="layui-input" id="textvideo">
    17. <div class="layui-input-suffix">
    18. <button class="layui-btn layui-btn-primary" id="videoLine" value="前台调用后台方法" onclick="vide()">前台调用后台方法button>
    19. div>
    20. div>
    21. div>
    22. <script src="layui-v2.9.7/layui.js">script>
    23. <script>
    24. document.getElementById('videoUpload').addEventListener('change', handleVideoUpload, false);
    25. function handleVideoUpload(event) {
    26. var url = document.getElementById('videoUpload').value;//获取file选择文件物理路径方法
    27. url = window.external.FileLode(url)
    28. //var file = event.target.files[0]; // 获取用户选择的文件
    29. //var videoURL = URL.createObjectURL(file); // 创建一个指向视频文件的 URL
    30. document.getElementById('videoUpload').value = url;
    31. //判断是否存在video标签
    32. if (document.getElementById('videofile')) {
    33. var element = document.getElementById("videofile");
    34. element.parentNode.removeChild(element);
    35. }
    36. // 创建一个 video 元素,用于播放视频
    37. var video = document.createElement('video');
    38. video.src = url;//videoURL; // 设置 video 元素的 src 属性为视频文件的 URL
    39. video.controls = true; // 显示视频控制器,如播放/暂停按钮等
    40. video.width = "500";
    41. video.height = "300";
    42. video.id = "videofile";
    43. video.play(); // 自动播放视频
    44. // 将 video 元素添加到页面中
    45. document.body.appendChild(video);
    46. }
    47. function handinitLine(text) {
    48. alert(text);
    49. }
    50. function vide() {
    51. var a = document.getElementById('textvideo').value;
    52. var url = window.external.videoLine(a);
    53. //判断是否存在video标签
    54. if (document.getElementById('videofile')) {
    55. var element = document.getElementById("videofile");
    56. element.parentNode.removeChild(element);
    57. }
    58. // 创建一个 video 元素,用于播放视频
    59. var video = document.createElement('video');
    60. video.src = url; // 设置 video 元素的 src 属性为视频文件的 URL
    61. video.controls = true; // 显示视频控制器,如播放/暂停按钮等
    62. video.width = "500";
    63. video.height = "300";
    64. video.id = "videofile";
    65. video.play(); // 自动播放视频
    66. // 将 video 元素添加到页面中
    67. document.body.appendChild(video);
    68. }
    69. function strbol(str) {
    70. if (str.indexOf('http') == 0) {
    71. //开头包含http
    72. return false;
    73. }
    74. return true;
    75. }
    76. script>
    77. body>

    FFmpegHelper类:视频转码类

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Diagnostics;
    4. using System.Linq;
    5. using System.Text;
    6. using System.Threading.Tasks;
    7. namespace DXApplication1.Helper
    8. {
    9. class FFmpegHelper
    10. {
    11. //安装的ffmpeg的路径 写在配置文件的 你也可以直接写你的路径 D:\ffmpeg\bin\ffmpeg.exe
    12. //static string FFmpegPath = System.Configuration.ConfigurationManager.AppSettings["ffmepg"];
    13. ///
    14. /// 视频转码为mp4文件
    15. ///
    16. ///
    17. ///
    18. public static void VideoToTs(string videoUrl, string targetUrl)
    19. {
    20. //视频转码指令
    21. string cmd = string.Format("ffmpeg -i \"{0}\" -y -ab 32 -ar 22050 -b 800000 -s 480*360 \"{1}\"", videoUrl, targetUrl);
    22. RunMyProcess(cmd);
    23. }
    24. ///
    25. /// 将ts文件转换为mu3u8文件
    26. ///
    27. ///
    28. /// 这个路径不要带扩展名
    29. /// 视频切片时长,默认5秒
    30. public static void TsToM3u8(string tsUrl, string m3u8Url, int videoLength = 5)
    31. {
    32. //这里是关键点,一般平时切视频都是用FFmpeg -i 地址 -c这样,但是在服务器时,这样调用可能找不到ffmpeg的路径 所以这里直接用ffmpeg.exe来执行命令
    33. //string cmd = $@"{FFmpegPath} -i {tsUrl} -c copy -map 0 -f segment -segment_list {m3u8Url}.m3u8 -segment_time 5 {m3u8Url}%03d.ts";
    34. string cmd = string.Format("ffmpeg -i \"{0}\" -c copy -map 0 -f segment -segment_list \"{1}.mp4\" -segment_time {2} \"{1}%03d.ts\"", tsUrl, m3u8Url, videoLength);
    35. RunMyProcess(cmd);
    36. }
    37. ///
    38. /// 生成MP4频的缩略图
    39. ///
    40. /// 视频文件地址
    41. /// 视频缩略图地址
    42. /// 宽和高参数,如:240*180
    43. /// ss后跟的时间单位为秒
    44. ///
    45. public static string CatchImg(string videoUrl, string imgUrl, int Second = 8, string imgSize = "1280x720")
    46. {
    47. try
    48. {
    49. //转换文件格式的同时抓缩微图:
    50. //ffmpeg - i "test.avi" - y - f image2 - ss 8 - t 0.001 - s 350x240 'test.jpg'
    51. //- ss后跟的时间单位为秒
    52. string cmd = string.Format("ffmpeg -i \"{0}\" -y -f image2 -ss {1} -t 0.001 -s {2} \"{3}\"", videoUrl, Second, imgSize, imgUrl);
    53. RunMyProcess(cmd);
    54. //注意:图片截取成功后,数据由内存缓存写到磁盘需要时间较长,大概在3,4秒甚至更长;
    55. //System.Threading.Thread.Sleep(500);
    56. if (System.IO.File.Exists(imgUrl))
    57. {
    58. return imgUrl;
    59. }
    60. return "";
    61. }
    62. catch
    63. {
    64. return "";
    65. }
    66. }
    67. ///
    68. /// 执行cmd指令
    69. ///
    70. ///
    71. public static void RunMyProcess(string Parameters)
    72. {
    73. using (Process p = new Process())
    74. {
    75. try
    76. {
    77. p.StartInfo.FileName = "cmd.exe";
    78. p.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动
    79. p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
    80. p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
    81. p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
    82. p.StartInfo.CreateNoWindow = false;//不创建进程窗口
    83. p.Start();//启动线程
    84. p.StandardInput.WriteLine(Parameters + "&&exit"); //向cmd窗口发送输入信息
    85. p.StandardInput.AutoFlush = true;
    86. p.StandardInput.Close();
    87. //获取cmd窗口的输出信息
    88. string output = p.StandardError.ReadToEnd(); //可以输出output查看具体报错原因
    89. p.WaitForExit();//等待完成
    90. p.Close();//关闭进程
    91. p.Dispose();//释放资源
    92. }
    93. catch (Exception ex)
    94. {
    95. throw ex;
    96. }
    97. }
    98. }
    99. }
    100. }

  • 相关阅读:
    初等数论——素数,逆元,EXGCD有关
    java学习day8(Java基础)static关键字和继承
    python项目开发常用的目录结构
    c++中的重载
    “合”而不同,持“智”以恒,幂律智能2022产品升级发布会全程回顾!
    ANDROID历年漏洞数量
    odoo wizard界面显示带复选框列表及勾选数据获取
    动物主题网页设计(学生期末作业必看)
    k8s免费在线集群工具
    jvm-java 内存模型 以及各个分区具体内容
  • 原文地址:https://blog.csdn.net/qq_60521457/article/details/136652418