最近公司有个项目想对接腾讯云直播。腾讯云直播的推流链接是在客户端生成的,所以这段代码就别指望调用API获取了。

遗憾的是,腾讯云的网站上,只给了Java和PHP的代码示例,并没有给出C#的代码示例:

而我实在看不懂他Java的代码实例中那个txTime参数是从哪冒出来的。自己试了试各种方案,最后终于猜出来,原来是自1970年到今天的总秒数。

剩下的就是求一下MD5,拼接字符串,转一下十六进制。都是体力活,拿C#写也不算费劲。

折腾一阵后,终于搞定。

using System;
using System.Security.Cryptography;
using System.Text;

namespace TencentCloud
{
    public class Program
    {
        // Any value is fine.
        public const string StreamAppName = "live";
        // Any value is fine.
        public const string StreamName = "mystreamname";
        // Get it from Tencent cloud.
        public const string Key = "yourkeyaaaaaaaaaaaaaaaaaa";
        // Get it from Tencent cloud.
        public const string Domain = "74371.livepush.myqcloud.com";
        public const string PlayDomain = "play.bopodastaging.top";

        public static void Main(string[] args)
        {
            // Stream
            var safeUrl = GetSafeUrl(
                key: Key,
                streamName: StreamName,
                txTime: DateTime.Now + TimeSpan.FromDays(1));

            var streamUrl = $"rtmp://{Domain}/{StreamAppName}/";
            var streamKey = $"{StreamName}?{safeUrl}";

            Console.WriteLine(streamUrl);
            Console.WriteLine(streamKey);

            // Play
            Console.WriteLine($"rtmp://{PlayDomain}/{StreamAppName}/{StreamName}");
            Console.WriteLine($"http://{PlayDomain}/{StreamAppName}/{StreamName}.flv");
            Console.WriteLine($"http://{PlayDomain}/{StreamAppName}/{StreamName}.m3u8");
        }

        private static string GetSafeUrl(string key, string streamName, DateTime txTime)
        {
            var textTime = ConvertToUnixTimestamp(txTime).ToString("X").ToUpper();

            var input = $"{key}{streamName}{textTime}";
            var txSecret = GetMD5(input);

            return $"txSecret={txSecret}&txTime={textTime}";
        }

        public static string GetMD5(string sourceString)
        {
            var data = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(sourceString));
            var sBuilder = new StringBuilder();
            foreach (var c in data)
            {
                sBuilder.Append(c.ToString("x2"));
            }
            return sBuilder.ToString();
        }

        private static int ConvertToUnixTimestamp(DateTime date)
        {
            var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var diff = date.ToUniversalTime() - origin;
            return (int)Math.Floor(diff.TotalSeconds);
        }
    }
}

运行效果: