You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WebView2中通过代码实现本地MP4视频循环播放?

WinForm WebView2 本地MP4自动循环播放解决方案

问题说明

在WinForm中使用WebView2播放本地MP4时,目前只能通过右键菜单手动开启循环,初始化窗体时循环选项默认未勾选。尝试设置WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS的--loop=true参数无效,需要用C#/VB.NET实现自动循环。

用户原VB.NET代码:

Imports System.Speech.Synthesis
Imports Microsoft.Web.WebView2.Core
Imports MySql.Data.MySqlClient

 Private Sub QDashboard_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.StartPosition = FormStartPosition.Manual
        Me.Location = Screen.AllScreens(1).Bounds.Location
        Environment.SetEnvironmentVariable("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", "--autoplay-policy=no-user-gesture-required --loop=true")'doesn't work :(
        InitializeComponent()
        Timer_count.Enabled = True
        Timer_update.Enabled = True
end Sub

有效解决方法

方法1:用HTML包裹视频实现循环

WebView2的--loop浏览器参数对直接加载本地MP4的场景不生效,最靠谱的方式是通过HTML5的loop属性控制循环:

  1. 新建一个本地HTML文件(比如video_player.html),内容如下:
<!DOCTYPE html>
<html>
<body style="margin:0;padding:0;">
    <video id="localVideo" width="100%" height="100%" autoplay muted loop>
        <source src="C:\你的视频路径\demo.mp4" type="video/mp4">
    </video>
</body>
</html>

将C:\你的视频路径\demo.mp4替换为实际的MP4文件路径,若HTML和MP4在同一目录,使用相对路径即可。

  1. 在WinForm中让WebView2加载该HTML文件:
' 放在InitializeComponent之后,或WebView2初始化完成的逻辑中
WebView21.Source = New Uri("file:///C:\HTML文件路径\video_player.html")

方法2:加载MP4后用JS开启循环

不想额外创建HTML文件的话,可直接加载MP4,待页面加载完成后执行JavaScript设置循环:

  1. 先让WebView2加载目标MP4:
WebView21.Source = New Uri("file:///C:\你的视频路径\demo.mp4")
  1. 给WebView2绑定NavigationCompleted事件,在事件中执行JS:
Private Async Sub WebView21_NavigationCompleted(sender As Object, e As CoreWebView2NavigationCompletedEventArgs) Handles WebView21.NavigationCompleted
    ' 找到页面中的video元素并开启循环
    Await WebView21.CoreWebView2.ExecuteScriptAsync("document.querySelector('video').loop = true;")
    ' 若需要自动播放,可添加以下语句
    Await WebView21.CoreWebView2.ExecuteScriptAsync("document.querySelector('video').play();")
End Sub

方法3:修正环境变量设置时机(仅辅助)

你之前设置环境变量的时机错误,WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS必须在WebView2的CoreWebView2初始化之前设置,建议在程序启动时配置:

' 修改到Program.vb的Main方法中
Sub Main()
    Environment.SetEnvironmentVariable("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", "--autoplay-policy=no-user-gesture-required")
    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault(False)
    Application.Run(New QDashboard())
End Sub

注意:即便设置对时机,--loop参数仍大概率对直接加载MP4的场景无效,优先采用前两种方法。

内容的提问来源于stack exchange,提问作者carl benz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 18:45:05