跳至主要內容

C#解析B站弹幕

MonoLogueChiC#dotnet大约 2 分钟

两年前写过写一篇文章,BiliBili 弹幕解析,但上次是解析 xml 弹幕,最近打算研究一下 v2 弹幕接口,使用的是 protobuf。

了解 protobuf

在本文正式开始之前要先了解一下 protobuf,这个可以自行搜索,本文不在赘述。

protobuf 定义

可以直接使用其他项目定义的,以下两个项目的定义文件均可直接使用,选择其一下载备用

实例

创建项目

创建一个控制台项目作为演示使用,并使用 nuget 安装相关包

将前面下载好的 protobuf 定义文件放入项目目录下,我创建的示例项目路径为 Models/Proto/dm.proto

修改项目文件,添加 protobuf 定义文件引用

<Project Sdk="Microsoft.NET.Sdk">

	<PropertyGroup>
		<OutputType>Exe</OutputType>
		<TargetFramework>net6.0</TargetFramework>
		<ImplicitUsings>enable</ImplicitUsings>
		<Nullable>enable</Nullable>
	</PropertyGroup>

	<ItemGroup>
		<PackageReference Include="Flurl" Version="3.0.6" />
		<PackageReference Include="Flurl.Http" Version="3.2.4" />
		<PackageReference Include="Google.Protobuf" Version="3.21.1" />
		<PackageReference Include="Grpc.Net.Client" Version="2.46.0" />
		<PackageReference Include="Grpc.Tools" Version="2.46.3">
			<PrivateAssets>all</PrivateAssets>
			<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
		</PackageReference>
	</ItemGroup>

+	<ItemGroup>
+		<Protobuf Include="Models\Proto\dm.proto" />
+	</ItemGroup>

</Project>

获取数据

使用 v2 弹幕接口 https://api.bilibili.com/x/v2/dm/list/seg.so 获取数据

using Flurl;
using Flurl.Http;

var a = await "https://api.bilibili.com/x/v2/dm/list/seg.so".SetQueryParams(new
{
    type = 1,
    oid = 1176840,
    segment_index = 1
}).GetBytesAsync();

解析数据

using Bilibili.Community.Service.Dm.V1;
using Flurl;
using Flurl.Http;

var a = await "https://api.bilibili.com/x/v2/dm/list/seg.so".SetQueryParams(new
{
    type = 1,
    oid = 1176840,
    segment_index = 1
}).GetBytesAsync();

var b = DmSegMobileReply.Parser.ParseFrom(a);

序列化数据

using Bilibili.Community.Service.Dm.V1;
using Flurl;
using Flurl.Http;
using Newtonsoft.Json;

var a = await "https://api.bilibili.com/x/v2/dm/list/seg.so".SetQueryParams(new
{
    type = 1,
    oid = 1176840,
    segment_index = 1
}).GetBytesAsync();

var b = DmSegMobileReply.Parser.ParseFrom(a);

var c = JsonConvert.SerializeObject(b);

打印数据

using Bilibili.Community.Service.Dm.V1;
using Flurl;
using Flurl.Http;
using Newtonsoft.Json;

var a = await "https://api.bilibili.com/x/v2/dm/list/seg.so".SetQueryParams(new
{
    type = 1,
    oid = 1176840,
    segment_index = 1
}).GetBytesAsync();

var b = DmSegMobileReply.Parser.ParseFrom(a);

var c = JsonConvert.SerializeObject(b);

Console.WriteLine(c);

Console.ReadKey();

至此,本文完结。