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); // 创建一个指向视频文件的 URLdocument.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 属性为视频文件的 URLvideo.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 属性为视频文件的 URLvideo.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) {//开头包含httpreturn 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;}}}}
}