随便找了一个翻译接口,给公众号赋个能。

百度翻译:https://fanyi-api.baidu.com/api/trans/product/index

工作流程:微信公众号在输入语音时,会自动识别并转为文字,我们的后端消息接收接口在收到微信服务器的消息推送后,取出已经转换好的文字消息,并调用翻译API即可实现翻译语音的功能。

Translate定义


public class TranslatePair
{
    [JsonPropertyName("src")]
    public string Source { get; set; }
    [JsonPropertyName("dst")]
    public string Destination { get; set; }
}
public class Translate
{
    [JsonPropertyName("from")]
    public string From { get; set; }
    [JsonPropertyName("to")]
    public string To { get; set; }
    [JsonPropertyName("trans_result")]
    public TranslatePair[] Result { get; set; }
    [JsonPropertyName("error_code")]
    public string ErrorCode { get; set; }
    [JsonPropertyName("error_msg")]
    public string ErrorMessage { get; set; }
}

封装翻译方法:


public static class Baidu
{
    public static Translate Translate(string q, bool fromEn = true)
    {
        string url = "http://api.fanyi.baidu.com/api/trans/vip/translate";
        q = q.Replace("\"", "").Replace("+", "");

        const string appid = "baidu-translate-appid";
        const string secret = "baidu-translate-appsecret";
        string salt = DateTime.Now.ToString("yyMMddHHmmssfff");
        string from = fromEn ? "en" : "zh";
        string to = fromEn ? "zh" : "en";
        string raw = $"{appid}{q}{salt}{secret}";
        using MD5 md5 = MD5.Create();
        string sign = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(raw))).Replace("-", "").ToLower();
        using WebClient client = new();
        client.Headers["Content-Type"] = "application/x-www-form-urlencoded";
        var resp = client.UploadData(url, Encoding.UTF8.GetBytes($"q={q}&from={from}&to={to}&appid={appid}&salt={salt}&sign={sign}"));
        string strResp = Encoding.UTF8.GetString(resp);
        Translate t = JsonSerializer.Deserialize<Translate>(strResp);
        return t;
    }
}

语音中译英:

文字中译英:

语音英译中:

文字英译中: