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

将JS代码转C#并解析该Protobuf相关函数功能

JavaScript转C#:Yandex视频翻译Protobuf编解码实现及功能解析

一、原JS代码功能解析

这段自执行函数是为Yandex视频翻译服务封装的Protobuf编解码工具,核心功能如下:

  • 定义Protobuf消息结构:声明了VideoTranslationRequest(请求)和VideoTranslationResponse(响应)两个Protobuf类型,严格对应服务端的字段编号与数据类型
  • 请求编码:encodeRequest方法接收视频URL、设备ID、未知参数unknown1,自动填充固定参数(unknown0=1、unknown2=1、language=en、unknown3=0、unknown4=0),将请求对象序列化为Protobuf二进制字节流,作为接口请求体发送
  • 响应解码:decodeResponse方法将服务端返回的二进制数据反序列化为可读的响应对象,提取返回的视频URL和状态码

二、C#转换实现

C#中推荐使用官方Google.Protobuf库实现Protobuf编解码,以下是完整实现方案:

1. 编写Protobuf定义文件(yandex.proto)

先定义符合原JS结构的proto文件,作为生成C#类的基础:

syntax = "proto3";
package yandex;

// 视频翻译请求消息
message VideoTranslationRequest {
  string url = 3;
  string deviceId = 4;
  int32 unknown0 = 5;
  fixed64 unknown1 = 6;
  int32 unknown2 = 7;
  string language = 8;
  int32 unknown3 = 9;
  int32 unknown4 = 10;
}

// 视频翻译响应消息
message VideoTranslationResponse {
  string url = 1;
  int32 status = 4;
}

2. 生成C#类

通过protoc工具或NuGet包Google.Protobuf.Tools自动生成C#类,避免手动编写错误。生成命令示例:

protoc --csharp_out=. yandex.proto

3. 封装编解码工具类

参照原JS逻辑,封装静态工具类实现编解码:

using Google.Protobuf;

public static class YandexRequests
{
    /// <summary>
    /// 编码视频翻译请求为Protobuf二进制字节数组
    /// </summary>
    /// <param name="url">待翻译视频的URL</param>
    /// <param name="deviceId">设备ID</param>
    /// <param name="unknown1">未知固定参数(原JS中传入的参数)</param>
    /// <returns>Protobuf编码后的字节数组</returns>
    public static byte[] EncodeRequest(string url, string deviceId, ulong unknown1)
    {
        var request = new Yandex.VideoTranslationRequest
        {
            Url = url,
            DeviceId = deviceId,
            Unknown0 = 1,
            Unknown1 = unknown1,
            Unknown2 = 1,
            Language = "en",
            Unknown3 = 0,
            Unknown4 = 0
        };

        return request.ToByteArray();
    }

    /// <summary>
    /// 解码Protobuf二进制响应为响应对象
    /// </summary>
    /// <param name="responseBytes">服务端返回的二进制响应数据</param>
    /// <returns>解析后的响应对象</returns>
    public static Yandex.VideoTranslationResponse DecodeResponse(byte[] responseBytes)
    {
        return Yandex.VideoTranslationResponse.Parser.ParseFrom(responseBytes);
    }
}

4. 使用示例

// 生成请求体(对应原JS的var body = yandexRequests.encodeRequest(...))
byte[] requestBody = YandexRequests.EncodeRequest("https://example.com/video.mp4", "device_123", 123456UL);

// 解码响应示例
byte[] responseData = /* 从Yandex服务获取的二进制响应 */;
Yandex.VideoTranslationResponse response = YandexRequests.DecodeResponse(responseData);
// 输出结果
Console.WriteLine($"翻译后视频URL:{response.Url}");
Console.WriteLine($"响应状态码:{response.Status}");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:35:30