Blazor组件自做十三: VideoPlayer 视频播放器

Video.js 是一个具有大量功能的流行的视频和音频 JavaScript 库,今天我们试试集成到 Blazor .

Blazor VideoPlayer 视频播放器 组件 Blazor组件自做十三: VideoPlayer 视频播放器插图

示例

https://blazor.app1.es/videoPlayers

1. 新建工程b13video

dotnet new blazorserver -o b13video

2. 将项目添加到解决方案中:

dotnet sln add b13video/b13video.csproj

3. Pages_Host.cshtml 引用 video-js.css


4. 接下来,Pages_Host.cshtml 引用 Video.js, 添加以下脚本文件到Pages_Host.cshtml






5. 添加 app.js 文件到 wwwroot文件夹

文件内容

function loadPlayer(id, options) {
  videojs(id, options);
}

6. Pages_Host.cshtml 引用 app.js


完整文件看起来应该是这样

@page "/"
@using Microsoft.AspNetCore.Components.Web
@namespace b13video.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

    
    
    
    
    
    
    
    
    

    

    
An error has occurred. This application may no longer respond until reloaded. An unhandled exception has occurred. See browser dev tools for details. Reload 🗙

7. Razor 页面, 我们直接在 Index.razor 里添加


跑一下

Blazor组件自做十三: VideoPlayer 视频播放器插图1

8. 封装

取消几行html组件设定,改为c#提供参数, 最终代码如下


@inject IJSRuntime jsRuntime
@code{
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await jsRuntime.InvokeVoidAsync("loadPlayer", "my-player", new
            {
                width = 600,
                height = 300,
                controls = true,
                autoplay = true,
                preload = "auto",
                poster = "//vjs.zencdn.net/v/oceans.png",
                sources = new[] {
                        new { type =  "application/x-mpegURL", src = "https://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8"},
                        new { type =  "video/mp4", src = "//vjs.zencdn.net/v/oceans.mp4"}
                }
            });
        }
    }

}

调试一下,成功运行就进入下一步.

9. 组件化. {最终代码,请大家直接使用CV大法}

PagesVideoPlayer.razor

@inject IJSRuntime jsRuntime
@namespace Blazor100.Components

@if (Debug) {
@info

}


PagesVideoPlayer.razor.cs

using b13video.Pages;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Options;
using Microsoft.JSInterop;
using System.Text.Json.Serialization;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Blazor100.Components; 

public partial class VideoPlayer : IAsyncDisposable
{
    [Inject] IJSRuntime? JS { get; set; }
    private IJSObjectReference? module;
    private DotNetObjectReference? instance { get; set; }
    protected ElementReference element { get; set; }
    private bool init;
    private string? info;

    private string Id { get; set; } = Guid.NewGuid().ToString();

    /// 
    /// 资源类型
    /// 
    [Parameter]
    public string? SourcesType { get; set; }

    /// 
    /// 资源地址
    /// 
    [Parameter]
    public string? SourcesUrl { get; set; }

    [Parameter]
    public int Width { get; set; } = 300;

    [Parameter]
    public int Height { get; set; } = 200;

    [Parameter]
    public bool Controls { get; set; } = true;

    [Parameter]
    public bool Autoplay { get; set; } = true;

    [Parameter]
    public string Preload { get; set; } = "auto";

    /// 
    /// 设置封面
    /// 
    [Parameter]
    public string? Poster { get; set; }

    [Parameter]
    public VideoPlayerOption? Option { get; set; }

    [Parameter]
    public bool Debug { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        try
        {
            if (firstRender)
            {
                module = await JS!.InvokeAsync("import", "./app.js");
                instance = DotNetObjectReference.Create(this);

                Option = Option ?? new VideoPlayerOption()
                {
                    Width = Width,
                    Height = Height,
                    Controls = Controls,
                    Autoplay = Autoplay,
                    Preload = Preload,
                    Poster = Poster,
                    //EnableSourceset= true,
                    //TechOrder= "['fakeYoutube', 'html5']"
                };
                Option.Sources.Add(new VideoSources(SourcesType, SourcesUrl));

                try
                {
                    await module.InvokeVoidAsync("loadPlayer", instance, "video_" + Id, Option);
                }
                catch (Exception e)
                {
                    info = e.Message;
                    if (Debug) StateHasChanged();
                    Console.WriteLine(info);
                    if (OnError != null) await OnError.Invoke(info);
                }
            }
        }
        catch (Exception e)
        {
            if (OnError != null) await OnError.Invoke(e.Message);
        }
    }

    async ValueTask IAsyncDisposable.DisposeAsync()
    {
        if (module is not null)
        {
            await module.InvokeVoidAsync("destroy", Id);
            await module.DisposeAsync();
        }
    }

    /// 
    /// 获得/设置 错误回调方法
    /// 
    [Parameter]
    public Func? OnError { get; set; }

    /// 
    /// JS回调方法
    /// 
    /// 
    /// 
    [JSInvokable]
    public void GetInit(bool init) => this.init = init;

    /// 
    /// JS回调方法
    /// 
    /// 
    /// 
    [JSInvokable]
    public async Task GetError(string error)
    {
        info = error;
        if (Debug) StateHasChanged();
        if (OnError != null) await OnError.Invoke(error);
    }

}

PagesVideoPlayerOption.cs

using System.Text.Json.Serialization;

namespace b13video.Pages
{
    public class VideoPlayerOption
    {
        [JsonPropertyName("width")]
        public int Width { get; set; } = 300;

        [JsonPropertyName("height")]
        public int Height { get; set; } = 200;

        [JsonPropertyName("controls")]
        public bool Controls { get; set; } = true;

        [JsonPropertyName("autoplay")]
        public bool Autoplay { get; set; } = true;

        [JsonPropertyName("preload")]
        public string Preload { get; set; } = "auto";

        /// 
        /// 播放资源
        /// 
        [JsonPropertyName("sources")]
        public List Sources { get; set; } = new List();

        /// 
        /// 设置封面
        /// 
        [JsonPropertyName("poster")]
        public string? Poster { get; set; } 

        //[JsonPropertyName("enableSourceset")]
        //public bool EnableSourceset { get; set; }

        //[JsonPropertyName("techOrder")]
        //public string? TechOrder { get; set; } = "['html5', 'flash']";

    }

    /// 
    /// 播放资源
    /// 
    public class VideoSources
    {
        public VideoSources() { }

        public VideoSources(string? type, string? src)
        {
            this.Type = type ?? throw new ArgumentNullException(nameof(type));
            this.Src = src ?? throw new ArgumentNullException(nameof(src));
        }

        /// 
        /// 资源类型video/mp4application/x-mpegURLvideo/youtube
        /// 
        [JsonPropertyName("type")]
        public string Type { get; set; } = "application/x-mpegURL";

        /// 
        /// 资源地址
        /// 
        [JsonPropertyName("src")]
        public string Src { get; set; } = "application/x-mpegURL";
    } 
}

wwwrootapp.js

var player = null;

export function loadPlayer(instance, id, options) {
    console.log('player id', id);
    player = videojs(id, options);

    player.ready(function () {
       console.log('player.ready');
       var promise = player.play();

        if (promise !== undefined) {
            promise.then(function () {
                console.log('Autoplay started!');
            }).catch(function (error) {
                console.log('Autoplay was prevented.', error);
                instance.invokeMethodAsync('GetError', 'Autoplay was prevented.'+ error);
            });
        }
        instance.invokeMethodAsync('GetInit', true);
    });

    return false;
}

export function destroy(id) {
    if (undefined !== player && null !== player) {
        player = null;
        console.log('destroy');
    }
}

10. 页面调用

项目源码

Github

知识共享许可协议

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名AlexChow(包含链接: https://github.com/densen2014 ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系

AlexChow

今日头条 | 博客园 | 知乎 | Gitee | GitHub

Blazor组件自做十三: VideoPlayer 视频播放器插图2


Blazor 组件

条码扫描 ZXingBlazor
Blazor组件自做十三: VideoPlayer 视频播放器插图3
Blazor组件自做十三: VideoPlayer 视频播放器插图4

图片浏览器 Viewer

条码扫描 BarcodeScanner

手写签名 Handwritten

手写签名 SignaturePad

定位/持续定位 Geolocation

屏幕键盘 OnScreenKeyboard

百度地图 BaiduMap

谷歌地图 GoogleMap

蓝牙和打印 Bluetooth

PDF阅读器 PdfReader

文件系统访问 FileSystem

光学字符识别 OCR

电池信息/网络信息 WebAPI

文章来源于互联网:Blazor组件自做十三: VideoPlayer 视频播放器

THE END
分享
二维码