当前位置: 首页 > news >正文

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); // 创建一个指向视频文件的 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;}}}}
}

http://www.lryc.cn/news/318785.html

相关文章:

  • Neo4j 批量导入数据 从官方文档学习LOAD CSV 命令 小白可食用版
  • Day43-2-企业级实时复制intofy介绍及实践
  • 2024年AI辅助研发趋势深度解析:科技革新与效率提升的双重奏
  • bash: mysqldump: command not found
  • hcie数通和云计算选哪个好?
  • 浅易理解:非极大抑制NMS
  • C语言如何进⾏字符数组的复制?
  • Linux 中搭建 主从dns域名解析服务器
  • CSS3病毒病原体图形特效
  • Tomcat Web 开发项目构建教程
  • Elasticsearch(9) gauss的使用
  • php前端和java后端数据调用流程
  • C语言从入门到熟悉------第四阶段
  • 【目标检测-数据集准备】DIOR转为yolo训练所需格式
  • Nacos为什么对于临时实例采用心跳检测,非临时实例采用主动询问?Nacos同时作为配置中心和注册中心有什么坏处?为什么Nacos可以抗住那么高的注册?
  • 【NLP】如何实现快速加载gensim word2vec的预训练的词向量模型
  • 前端实例:页面布局1(后端数据实现)
  • 【调参】如何为神经网络选择最合适的学习率lr-LRFinder-for-Keras
  • 【设计模式】Java 设计模式之享元模式(Flyweight)
  • 异次元发卡源码系统/荔枝发卡V3.0二次元风格发卡网全开源源码
  • 腾讯春招后端一面(八股篇)
  • “风口”上的量化大厂“绣球”抛向中低频人才
  • obdiag如何实现一键采集20+故障场景的诊断信息——《OceanBase诊断系列》之九
  • Cookie和Session的获取方法
  • 旅游市场游客满意度调查报告
  • 为什么选用python开发web?
  • C# Chart曲线控件专题
  • Spring:StopWatch
  • 考研C语言复习进阶(5)
  • [uni-app] 小程序码转为二维码, 小程序解析此码获取数据