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.Log;
  9. namespace WingASRService.Tencent
  10. {
  11. public class ASRApi
  12. {
  13. private ASRApi(){}
  14. public static (string message, bool isSuccess) CallASRApi(string url, string fileType)
  15. {
  16. try
  17. {
  18. // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
  19. // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
  20. Credential cred = new Credential {
  21. SecretId = "AKIDgDUVFbjbDahYAXeV6RXNxHK8gy0mJabN",
  22. SecretKey = "XprdARRBgusa3GEwObYFgrmRq0uYv3vY"
  23. };
  24. // Credential cred = new Credential {
  25. // SecretId = "AKIDMSIsADUUpvJGwJOKvsb5IDrGtGNBRzzi",
  26. // SecretKey = "4sQhdJBl5HI7f3oLbZIlwqXOyILyLWP0"
  27. // };
  28. // 实例化一个client选项,可选的,没有特殊需求可以跳过
  29. ClientProfile clientProfile = new ClientProfile();
  30. // 实例化一个http选项,可选的,没有特殊需求可以跳过
  31. HttpProfile httpProfile = new HttpProfile();
  32. httpProfile.Endpoint = ("asr.tencentcloudapi.com");
  33. clientProfile.HttpProfile = httpProfile;
  34. // 实例化要请求产品的client对象,clientProfile是可选的
  35. AsrClient client = new AsrClient(cred, "", clientProfile);
  36. // 实例化一个请求对象,每个接口都会对应一个request对象
  37. SentenceRecognitionRequest req = new SentenceRecognitionRequest();
  38. req.ProjectId = 0;
  39. req.SubServiceType = 2;
  40. req.EngSerViceType = "16k_zh_medical";
  41. req.SourceType = 0;
  42. req.Url = url;
  43. req.VoiceFormat = fileType;
  44. req.UsrAudioKey = "any";
  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 code:{errorCode} message:{errorMessage}");
  59. return (message: errorMessage, isSuccess: false);
  60. }
  61. }
  62. Logger.WriteLineError($"ASRApi.CallASRApi error {e}");
  63. return (message: "Unknow error", isSuccess: false);;
  64. }
  65. }
  66. }
  67. }