ASRApi.cs 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.Linq;
  2. using System.Text.RegularExpressions;
  3. using Newtonsoft.Json.Linq;
  4. using TencentCloud.Asr.V20190614;
  5. using TencentCloud.Asr.V20190614.Models;
  6. using TencentCloud.Common;
  7. using TencentCloud.Common.Profile;
  8. using WingServerCommon.Config;
  9. using WingServerCommon.Config.Parameters;
  10. using WingServerCommon.Log;
  11. namespace WingASRService.Tencent
  12. {
  13. public class ASRApi
  14. {
  15. private ASRApi() { }
  16. public static (string message, bool isSuccess) CallASRApi(string url, string fileType)
  17. {
  18. try
  19. {
  20. // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
  21. // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
  22. Credential cred = new Credential
  23. {
  24. SecretId = EnvironmentConfigManager.GetParammeter<StringParameter>("ASR", "AppKey").Value,
  25. SecretKey = EnvironmentConfigManager.GetParammeter<StringParameter>("ASR", "AppSecret").Value
  26. };
  27. // 实例化一个client选项,可选的,没有特殊需求可以跳过
  28. ClientProfile clientProfile = new ClientProfile();
  29. // 实例化一个http选项,可选的,没有特殊需求可以跳过
  30. HttpProfile httpProfile = new HttpProfile();
  31. httpProfile.Endpoint = ("asr.tencentcloudapi.com");
  32. clientProfile.HttpProfile = httpProfile;
  33. // 实例化要请求产品的client对象,clientProfile是可选的
  34. AsrClient client = new AsrClient(cred, "", clientProfile);
  35. // 实例化一个请求对象,每个接口都会对应一个request对象
  36. SentenceRecognitionRequest req = new SentenceRecognitionRequest();
  37. req.ProjectId = 0;
  38. req.SubServiceType = 2;
  39. req.EngSerViceType = "16k_zh_medical";
  40. req.SourceType = 0;
  41. req.Url = url;
  42. req.VoiceFormat = fileType;
  43. req.UsrAudioKey = "any";
  44. req.ConvertNumMode = 3;
  45. // 返回的resp是一个SentenceRecognitionResponse的实例,与请求对象对应
  46. var resp = client.SentenceRecognitionSync(req);
  47. return (message: resp.Result, isSuccess: true);
  48. }
  49. catch (Exception e)
  50. {
  51. var regMatch = Regex.Match(e.Message, @".*code:([.\w]+)[\s]+.*");
  52. if (regMatch.Groups.Count > 1)
  53. {
  54. var errorCode = regMatch.Groups[1].Value;
  55. if (!string.IsNullOrWhiteSpace(errorCode) && ASRErrorCode.ErrorsDictionary.Keys.Contains(errorCode))
  56. {
  57. var errorMessage = ASRErrorCode.ErrorsDictionary[errorCode];
  58. Logger.WriteLineError($"ASRApi.CallASRApi url:{url} code:{errorCode} message:{errorMessage}");
  59. return (message: errorMessage, isSuccess: false);
  60. }
  61. }
  62. Logger.WriteLineError($"ASRApi.CallASRApi url:{url} error {e}");
  63. return (message: "Unknow error", isSuccess: false); ;
  64. }
  65. }
  66. }
  67. }