WebUI 调用本地视频播放器

本页面详细介绍 WebUI 调用本地视频播放器的功能说明、使用方法及注意事项,为用户提供完整的操作指引。

1. 功能概述

WebUI 支持通过自定义协议(如 vlc:*potplayer:*)唤起用户设备上已安装的本地视频播放器(如 VLC、PotPlayer),直接播放下载任务中指定视频文件的 HTTP 链接。该功能可规避浏览器播放组件的格式限制,充分利用本地播放器的高级功能。

2. 核心优势

  1. 格式兼容性强:支持播放浏览器原生不支持的特殊格式视频(如 MKV、FLV 高清格式)。

  2. 功能更丰富:可调用本地播放器的高级解码、多音轨切换、字幕调节、倍速播放等专属功能。

  3. 性能提升:本地播放器可调用硬件加速功能,提升大码率视频的播放流畅度。

3. 前置条件

以下条件需全部满足,否则无法正常唤起本地播放器。

  1. 本地设备已安装支持的视频播放器(官方推荐:VLC 媒体播放器PotPlayer)。

  2. 播放器已完成自定义协议注册(如 vlc:// 协议需关联 VLC 播放器)。注册方法参考下一节。

  3. 浏览器未拦截自定义协议调用(首次使用时,浏览器可能弹出提示,需选择“允许”或“始终允许”)。

4. 附录:协议注册方法

4.1 VLC 播放器协议注册

正常安装 VLC 播放器后,还需使用以下批处理文件注册自定义协议:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

:: This installer writes a fixed protocol handler under Program Files so the
:: browser-supplied URL is never inserted into PowerShell source code.
fltmc >nul 2>&1 || (
    echo ERROR: This script requires Administrator privileges.
    echo Please right-click it and select "Run as administrator".
    pause
    exit /b 1
)

:: Locate VLC in either registry view before changing the protocol handler.
set "player_exe="
for /f "tokens=2,*" %%A in ('reg.exe query "HKLM\SOFTWARE\VideoLAN\VLC" /ve 2^>nul ^| findstr.exe /R /C:"REG_SZ"') do set "player_exe=%%B"
if not defined player_exe for /f "tokens=2,*" %%A in ('reg.exe query "HKLM\SOFTWARE\WOW6432Node\VideoLAN\VLC" /ve 2^>nul ^| findstr.exe /R /C:"REG_SZ"') do set "player_exe=%%B"

if not defined player_exe (
    echo ERROR: VLC installation information was not found.
    pause
    exit /b 1
)
if not exist "%player_exe%" (
    echo ERROR: VLC executable was not found: %player_exe%
    pause
    exit /b 1
)
echo Found VLC executable: %player_exe%

:: Install the embedded handler in an administrator-protected directory.
set "install_dir=%ProgramFiles%\BitComet\tools"
set "handler_path=%install_dir%\vlc_protocol_handler.ps1"
if not exist "%install_dir%" mkdir "%install_dir%" >nul 2>&1
if not exist "%install_dir%" (
    echo ERROR: Failed to create handler directory: %install_dir%
    pause
    exit /b 1
)

set "VLC_INSTALLER_SOURCE=%~f0"
set "VLC_HANDLER_PATH=%handler_path%"
powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "$ErrorActionPreference = 'Stop'; $lines = [IO.File]::ReadAllLines($env:VLC_INSTALLER_SOURCE); $begin = [Array]::IndexOf($lines, '# POWERSHELL_HANDLER_BEGIN'); $end = [Array]::IndexOf($lines, '# POWERSHELL_HANDLER_END'); if ($begin -lt 0 -or $end -le ($begin + 1)) { throw 'Embedded handler markers are invalid.' }; $payload = $lines[($begin + 1)..($end - 1)]; $temp = $env:VLC_HANDLER_PATH + '.tmp'; [IO.File]::WriteAllLines($temp, $payload, (New-Object Text.UTF8Encoding($false))); Move-Item -LiteralPath $temp -Destination $env:VLC_HANDLER_PATH -Force"
if errorlevel 1 (
    echo ERROR: Failed to install the VLC protocol handler.
    pause
    exit /b 1
)
set "VLC_INSTALLER_SOURCE="
set "VLC_HANDLER_PATH="

:: Register the protocol machine-wide. The URL remains a quoted argument to a
:: fixed -File script and is never parsed as part of a -Command expression.
set "powershell_exe=%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe"
set "protocol_command=\"%powershell_exe%\" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"%handler_path%\" \"%%1\""
reg.exe add "HKLM\SOFTWARE\Classes\vlc" /ve /t REG_SZ /d "URL:VLC Protocol" /f >nul || goto :registration_failed
reg.exe add "HKLM\SOFTWARE\Classes\vlc" /v "URL Protocol" /t REG_SZ /d "" /f >nul || goto :registration_failed
reg.exe add "HKLM\SOFTWARE\Classes\vlc\shell\open\command" /ve /t REG_SZ /d "%protocol_command%" /f >nul || goto :registration_failed

echo VLC protocol registered successfully.
echo Handler installed at: %handler_path%
endlocal
pause
exit /b 0

:registration_failed
echo ERROR: Failed to write the VLC protocol registration.
endlocal
pause
exit /b 1

# POWERSHELL_HANDLER_BEGIN
param(
    [Parameter(Mandatory = $true, Position = 0)]
    [string] $ProtocolUrl
)

Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'

# Convert the custom protocol value into one validated HTTP(S) media URL.
function ConvertFrom-VlcProtocolUrl {
    param(
        [Parameter(Mandatory = $true)]
        [string] $Value
    )

    $prefix = 'vlc://'
    if ([string]::IsNullOrWhiteSpace($Value) -or
        -not $Value.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {
        throw 'The VLC protocol URL must start with vlc://.'
    }

    $target = $Value.Substring($prefix.Length)

    # Browsers serialize vlc://http://... as vlc://http//...; restore only
    # the two explicitly supported inner schemes before URI validation.
    if ($target.StartsWith('http//', [StringComparison]::OrdinalIgnoreCase)) {
        $target = 'http://' + $target.Substring('http//'.Length)
    }
    elseif ($target.StartsWith('https//', [StringComparison]::OrdinalIgnoreCase)) {
        $target = 'https://' + $target.Substring('https//'.Length)
    }

    $uri = $null
    if (-not [Uri]::TryCreate($target, [UriKind]::Absolute, [ref] $uri)) {
        throw 'The VLC protocol target is not an absolute URL.'
    }

    if (($uri.Scheme -ne 'http' -and $uri.Scheme -ne 'https') -or
        [string]::IsNullOrWhiteSpace($uri.Host) -or
        -not [string]::IsNullOrEmpty($uri.UserInfo)) {
        throw 'Only HTTP(S) URLs without embedded credentials are allowed.'
    }

    return $uri.AbsoluteUri
}

# Read VLC's executable path from protected HKLM registry views.
function Get-VlcExecutablePath {
    $views = @(
        [Microsoft.Win32.RegistryView]::Registry64,
        [Microsoft.Win32.RegistryView]::Registry32
    )

    foreach ($view in $views) {
        $baseKey = $null
        $vlcKey = $null
        try {
            $baseKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey(
                [Microsoft.Win32.RegistryHive]::LocalMachine,
                $view
            )
            $vlcKey = $baseKey.OpenSubKey('SOFTWARE\VideoLAN\VLC')
            if ($null -eq $vlcKey) {
                continue
            }

            $candidate = [string] $vlcKey.GetValue('')
            if (-not [string]::IsNullOrWhiteSpace($candidate) -and
                (Test-Path -LiteralPath $candidate -PathType Leaf)) {
                return $candidate
            }
        }
        finally {
            if ($null -ne $vlcKey) {
                $vlcKey.Dispose()
            }
            if ($null -ne $baseKey) {
                $baseKey.Dispose()
            }
        }
    }

    throw 'VLC executable was not found.'
}

# HANDLER_MAIN_BEGIN
try {
    $targetUrl = ConvertFrom-VlcProtocolUrl -Value $ProtocolUrl
    $playerExe = Get-VlcExecutablePath

    # The executable and URL are separate arguments; no dynamic code is used.
    & $playerExe $targetUrl
}
catch {
    Write-Error $_.Exception.Message
    exit 1
}
# POWERSHELL_HANDLER_END

将以上代码保存为 vlc_reg_v2.bat,右键单击并选择“以管理员身份运行”。用户只需保存并运行这一个 BAT 文件;脚本会把内嵌的 PowerShell 处理程序安装到 %ProgramFiles%\BitComet\tools\vlc_protocol_handler.ps1,并注册 VLC 自定义协议。

4.2 PotPlayer 播放器协议注册

正常安装 PotPlayer 播放器(64 位版)后,默认已配置 potplayer 自定义协议。如果自定义协议失效,可使用以下批处理文件进行修复:

@echo off
setlocal enabledelayedexpansion

:: Check if the script is running with Administrator privileges
fltmc >nul 2>&1 || (
    echo ERROR: This script requires Administrator privileges!
    echo Please right-click and select "Run as administrator".
    pause
    exit /b 1
)

:: Find PotPlayer installation directory
for /f "tokens=1,2* delims=:" %%a in (
  'reg query "HKLM\SOFTWARE\DAUM\PotPlayer64" /v "ProgramPath" 2^>nul ^| findstr "ProgramPath"'
) do (
  for /f "tokens=1,2,3" %%l in ("%%a") do (
    set "player_disk=%%n"
  )
  set "player_exe=!player_disk!:%%b"
)

:: Verify PotPlayerMini64.exe exists
if not exist "!player_exe!" (
  echo PotPlayer executable not found: !player_exe!
  pause
  exit /b 1
) else (
  echo Found PotPlayer executable path: !player_exe!
)

:: Start registering registry entries

:: Create potplayer root key with default value
reg add "HKCR\potplayer" /ve /t REG_SZ /d "URL:PotPlayer Protocol" /f >nul

:: Create URL Protocol entry (empty value)
reg add "HKCR\potplayer" /v "URL Protocol" /t REG_SZ /d "" /f >nul

:: Create shell\open\command entry with properly quoted executable path
reg add "HKCR\potplayer\shell\open\command" /ve /t REG_SZ /d "\"!player_exe!\" \"%%1\"" /f >nul

:: Verify registration result
if %errorlevel% equ 0 (
  echo PotPlayer protocol registered successfully!
) else (
  echo Failed to write to registry. Please run this script as Administrator.
  pause
  exit /b 1
)

endlocal
pause

将此 BAT 文件保存到本地后,右键单击“以管理员权限运行”,即可注册 PotPlayer 自定义协议。