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

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

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

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

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

设计:

 后台代码:

注意:视频地址需要修改

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using WebKit;
using System.IO;
using DXApplication1.Helper;

namespace DXApplication1
{
    //为了使网页能够与winform交互 将com的可访问性设置为真
    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class webBrowser : DevExpress.XtraEditors.XtraForm
    {
        public webBrowser()
        {
            InitializeComponent();
           
        }

        private void webBrowser_Load(object sender, EventArgs e)
        {
            webBrowser1.ScriptErrorsSuppressed = true;//消除脚本错误 
            webBrowser1.Navigate(@"C:\source\repos\DXApplication1\DXApplication1\Html\HTMLPage2.html");
            webBrowser1.ObjectForScripting = this;
            
        }
        
        public string FileLode(string url)
        {
            //返回路径
            string result = url;
            if (!string.IsNullOrEmpty(url))
            {
                //保存文件名称
                string saveName = Guid.NewGuid().ToString() + ".mp4"; 
                string basePath = "UploadFile";
                string saveDir = DateTime.Now.ToString("yyyy-MM-dd");
                //获取应用程序的当前工作目录
                string MapPath = Directory.GetCurrentDirectory();
                // 文件上传后的保存路径
                string serverDir = Path.Combine(MapPath, basePath, saveDir);
                //保存文件完整路径
                string fileNme = Path.Combine(serverDir, saveName);
                //项目中是否存在文件夹,不存在创建                                                                                        
                if (!Directory.Exists(serverDir)) 
                {
                    Directory.CreateDirectory(serverDir);
                }
                //进行视频转换
                FFmpegHelper.VideoToTs( url, fileNme);
                result = fileNme;
            }
            
            return result;
        }

        /// <summary>
        /// 前台调用后台返回数据
        /// 注意:前台调用的方法不能:static
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        public string videoLine(int  a)
        {
            var result = string.Empty;
            switch (a)
            {
                case 1:
                    result = "http:/UploadFile/2024-03-12/17577f56-d999-4bbe-b67a-2156e241170d.mp4";
                    break;
                case 2:
                    result = "http:/UploadFile/2024-03-12/af67f8d3-ac79-4bd1-aa41-0743015ef9a4.m4v";
                    break;
                default:
                    result= "C:\\source\\repos\\DXApplication1\\DXApplication1\\video\\231127.m4v";
                    break;
            }
            return result;


        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            var url=textBox1.Text;
            if (!string.IsNullOrEmpty(url))
            {
                webBrowser1.ScriptErrorsSuppressed = true;
                webBrowser1.Navigate(url);
                webBrowser1.ObjectForScripting = this;
            }
            

        }
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            //调用前台js方法
            webBrowser1.Document.InvokeScript("handinitLine", new object[] { "后台调用js方法1" });
        }
    }
}

Html代码:

<!DOCTYPE html>

<head>
    <meta charset="utf-8" />
    <!--最高级模式渲染文档-->
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title></title>
    <link href="layui-v2.9.7/css/layui.css" rel="stylesheet" />
</head>
<body>
    <!--<div id="player">-->
    <!--播放本地视频-->
    <!--<video controls width="500" height="300" src="../video/1699408632422.m4v"></video>-->
    <!--播放网络视频-->
    <!--<video controls width="500" height="300" src="http:/UploadFile/2024-03-12/b7962018-26b3-43c1-83ad-aa2c14149f58.m4v"></video>-->
    <!--</div>-->

    <div>
        <input type="file" class="layui-btn layui-btn-primary" id="videoUpload" accept="video/*">
    </div>

    <div class="layui-form-item">
        <div class="layui-input-group">
            <div class="layui-input-split layui-input-prefix">
                
            </div>
            <input type="text" placeholder="" class="layui-input" id="textvideo">
            <div class="layui-input-suffix">
                <button class="layui-btn layui-btn-primary" id="videoLine" value="前台调用后台方法" onclick="vide()">前台调用后台方法</button>
            </div>
        </div>
    </div>



    <script src="layui-v2.9.7/layui.js"></script>
    <script>
        document.getElementById('videoUpload').addEventListener('change', handleVideoUpload, false);

        function handleVideoUpload(event) {
           
            var url = document.getElementById('videoUpload').value;//获取file选择文件物理路径方法
            url = window.external.FileLode(url)
            //var file = event.target.files[0]; // 获取用户选择的文件
            //var videoURL = URL.createObjectURL(file); // 创建一个指向视频文件的 URL
            document.getElementById('videoUpload').value = url;
            //判断是否存在video标签
            if (document.getElementById('videofile')) {
                var element = document.getElementById("videofile");
                element.parentNode.removeChild(element);
            }
            // 创建一个 video 元素,用于播放视频
            var video = document.createElement('video');
            video.src = url;//videoURL; // 设置 video 元素的 src 属性为视频文件的 URL
            video.controls = true; // 显示视频控制器,如播放/暂停按钮等
            video.width = "500";
            video.height = "300";
            video.id = "videofile";
            video.play(); // 自动播放视频
            // 将 video 元素添加到页面中
            document.body.appendChild(video);
           
        }
        function handinitLine(text) {
            alert(text);
        }
        function vide() {
            var a = document.getElementById('textvideo').value;
            var url = window.external.videoLine(a);
            //判断是否存在video标签
            if (document.getElementById('videofile')) {
                var element = document.getElementById("videofile");
                element.parentNode.removeChild(element);
            }
            // 创建一个 video 元素,用于播放视频
            var video = document.createElement('video');
            video.src = url; // 设置 video 元素的 src 属性为视频文件的 URL
            video.controls = true; // 显示视频控制器,如播放/暂停按钮等
            video.width = "500";
            video.height = "300";
            video.id = "videofile";
            video.play(); // 自动播放视频
            // 将 video 元素添加到页面中
            document.body.appendChild(video);

        }
        function strbol(str) {
            if (str.indexOf('http') == 0) {
                //开头包含http
                return false;
            }
            return true;
        }
    </script>
</body>

FFmpegHelper类:视频转码类

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DXApplication1.Helper
{
    class FFmpegHelper
    {
        //安装的ffmpeg的路径 写在配置文件的 你也可以直接写你的路径 D:\ffmpeg\bin\ffmpeg.exe
        //static string FFmpegPath = System.Configuration.ConfigurationManager.AppSettings["ffmepg"];

        /// <summary>
        /// 视频转码为mp4文件
        /// </summary>
        /// <param name="videoUrl"></param>
        /// <param name="targetUrl"></param>
        public static void VideoToTs(string videoUrl, string targetUrl)
        {
            //视频转码指令
            string cmd = string.Format("ffmpeg  -i \"{0}\" -y -ab 32 -ar 22050 -b 800000 -s 480*360 \"{1}\"", videoUrl, targetUrl);
            RunMyProcess(cmd);
        }

        /// <summary>
        /// 将ts文件转换为mu3u8文件
        /// </summary>
        /// <param name="tsUrl"></param>
        /// <param name="m3u8Url">这个路径不要带扩展名</param>
        /// <param name="videoLength">视频切片时长,默认5秒</param>
        public static void TsToM3u8(string tsUrl, string m3u8Url, int videoLength = 5)
        {
            //这里是关键点,一般平时切视频都是用FFmpeg -i  地址 -c这样,但是在服务器时,这样调用可能找不到ffmpeg的路径 所以这里直接用ffmpeg.exe来执行命令
            //string cmd = $@"{FFmpegPath} -i {tsUrl} -c copy -map 0 -f segment -segment_list {m3u8Url}.m3u8 -segment_time 5 {m3u8Url}%03d.ts";
            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);
            RunMyProcess(cmd);
        }

        /// <summary>
        /// 生成MP4频的缩略图
        /// </summary>
        /// <param name="videoUrl">视频文件地址</param>
        /// <param name="imgUrl">视频缩略图地址</param>
        /// <param name="imgSize">宽和高参数,如:240*180</param>
        /// <param name="Second">ss后跟的时间单位为秒</param>
        /// <returns></returns>
        public static string CatchImg(string videoUrl, string imgUrl, int Second = 8, string imgSize = "1280x720")
        {
            try
            {
                //转换文件格式的同时抓缩微图: 
                //ffmpeg - i "test.avi" - y - f image2 - ss 8 - t 0.001 - s 350x240 'test.jpg'
                //- ss后跟的时间单位为秒

                string cmd = string.Format("ffmpeg -i \"{0}\" -y -f image2 -ss {1} -t 0.001 -s {2} \"{3}\"", videoUrl, Second, imgSize, imgUrl);
                RunMyProcess(cmd);

                //注意:图片截取成功后,数据由内存缓存写到磁盘需要时间较长,大概在3,4秒甚至更长;
                //System.Threading.Thread.Sleep(500);
                if (System.IO.File.Exists(imgUrl))
                {
                    return imgUrl;
                }
                return "";
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 执行cmd指令
        /// </summary>
        /// <param name="Parameters"></param>
        public static void RunMyProcess(string Parameters)
        {
            using (Process p = new Process())
            {
                try
                {
                    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 = false;//不创建进程窗口                                                
                    p.Start();//启动线程
                    p.StandardInput.WriteLine(Parameters + "&&exit"); //向cmd窗口发送输入信息
                    p.StandardInput.AutoFlush = true;
                    p.StandardInput.Close();
                    //获取cmd窗口的输出信息
                    string output = p.StandardError.ReadToEnd(); //可以输出output查看具体报错原因

                    p.WaitForExit();//等待完成
                    p.Close();//关闭进程
                    p.Dispose();//释放资源

                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }
}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-16 06:20:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-16 06:20:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-16 06:20:04       82 阅读
  4. Python语言-面向对象

    2024-03-16 06:20:04       91 阅读

热门阅读

  1. 相机学习的知识积累

    2024-03-16 06:20:04       43 阅读
  2. Go 优雅判断 interface 是否为 nil

    2024-03-16 06:20:04       42 阅读
  3. uni-app 安卓手机判断是否开启相机相册权限

    2024-03-16 06:20:04       42 阅读
  4. Thinkphp+workman+redis实现多线程异步任务处理

    2024-03-16 06:20:04       39 阅读
  5. 单例模式详解

    2024-03-16 06:20:04       44 阅读
  6. springboot的自动配置原理

    2024-03-16 06:20:04       50 阅读
  7. apache和tomcat的优化总结概述

    2024-03-16 06:20:04       38 阅读
  8. 如何判断两个表的结构相同?desc t1 和desc t2

    2024-03-16 06:20:04       39 阅读
  9. SpringBoot3下Kafka分组均衡消费实现

    2024-03-16 06:20:04       43 阅读
  10. mysql 查询字段大于某长度的SQL

    2024-03-16 06:20:04       36 阅读