private string tempStr = ""; // temporary directory to store the converted audio file private void StartRecognize(string apiRecord) { WavInfo wav = ClassUtils.GetWavInfo(apiRecord); //数据量 = (采样频率 × 采样位数 × 声道数 × 时间) / 8 //if ((double)(wav.datasize * 8) / (wav.dwsamplespersec * wav.wbitspersample * wav.wchannels) > 60) //{ // labelInfo.ForeColor = Color.HotPink; // labelInfo.Text = "Error: The audio file is too large!"; //} // 非8k/16k, 16bit 位深, 单声道的,进行格式转换 if (apiRecord.EndsWith(".mp3", StringComparison.CurrentCultureIgnoreCase) || int.Parse(wav.dwsamplespersec.ToString()) != 16000 || int.Parse(wav.wbitspersample.ToString()) != 16 || int.Parse(wav.wchannels.ToString()) != 1) { apiRecord = ClassUtils.Convert2Wav(apiRecord); // convert audio file to 16k,16bit wav tempStr = apiRecord; } labelInfo.ForeColor = Color.SpringGreen; labelInfo.Text = "Recognizing..."; KeyValuePair <string, string> keyVal = (KeyValuePair <string, string>)comboBoxLan.SelectedItem; speechModel.APILanguage = keyVal.Value; // fetch the value in comboBox if (backgroundWorker.IsBusy != true) { this.backgroundWorker.RunWorkerAsync(); // do the time consuming task } }
/// <summary> /// 获取百度认证口令码 /// </summary> /// <returns>百度认证口令码: accessToken</returns> public string GetStrAccess() { string accessHtml = null; string accessToken = null; string[] accessTokenInfo = new string[2]; // string getAccessUrl = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" + //"&client_id=" + speechModel.APIKey + "&client_secret=" + speechModel.APISecretKey; string getAccessUrl = $"https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id={speechModel.APIKey}&client_secret={speechModel.APISecretKey}"; try { HttpWebRequest getAccessRequest = WebRequest.Create(getAccessUrl) as HttpWebRequest; getAccessRequest.ContentType = "multipart/form-data"; getAccessRequest.Accept = "*/*"; getAccessRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)"; getAccessRequest.Timeout = 30000; // timeout after 30s getAccessRequest.Method = "post"; HttpWebResponse response = getAccessRequest.GetResponse() as HttpWebResponse; using (StreamReader strHttpResponse = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { accessHtml = strHttpResponse.ReadToEnd(); } } catch (WebException ex) { MessageBox.Show(ex.ToString()); } JObject jo = JObject.Parse(accessHtml); accessToken = jo["access_token"].ToString(); // parse to get token int expiresIn = 2592000; // expire in: 2592000, one month // record the token request time long totalSeconds = ClassUtils.CurrentTime2Second(); accessTokenInfo[0] = accessToken; accessTokenInfo[1] = (totalSeconds + expiresIn).ToString(); // the expired time // write the token information into file File.WriteAllLines(@".\token.dat", accessTokenInfo); return(accessToken); /* JObject after parsing: * {{ * "access_token": "24.fd8c2088ac28b2722403c1acc36797e9.2592000.1487243775.282335-8317833", * "session_key": "9mzdCSCKQicpJZhQpgi/4cz7biI1uBSCE5PlgR4wdEq4NErxkOJQA3uJq2sTjY7SSKK8J0rsxOD18B5ugOj7QClCxwDt", * "scope": "public audio_voice_assistant_get audio_tts_post wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian", * "refresh_token": "25.68c6dc99cb375b786b030d156d51cccb.315360000.1782910269.282335-6432116", * "session_secret": "443304340f3b40e766006aa319732096", * "expires_in": 2592000 * }} */ }
private void Form1_Load(object sender, EventArgs e) { // add data to comboBox List <KeyValuePair <string, string> > listItems = new List <KeyValuePair <string, string> >(); listItems.Add(new KeyValuePair <string, string>("English", "en")); listItems.Add(new KeyValuePair <string, string>("中文", "zh")); listItems.Add(new KeyValuePair <string, string>("粤语", "ct")); comboBoxLan.DataSource = listItems; comboBoxLan.DisplayMember = "Key"; comboBoxLan.ValueMember = "Value"; comboBoxLan.SelectedIndex = 0; // binding the event to achieve Asynchronization backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork); backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted); // obtain token from file, avoid too many requests on remote server if (!File.Exists(@".\token.dat")) { accessToken = testASR.GetStrAccess(); // token file does not exist, send a request } else { string[] tokenInfo = File.ReadAllLines(@".\token.dat"); // check if the token has expired if (Convert.ToInt32(tokenInfo[1]) > ClassUtils.CurrentTime2Second()) { accessToken = tokenInfo[0]; } else { accessToken = testASR.GetStrAccess(); // expired, request again to refresh } } speechModel.APIAccessToken = accessToken; // update token in model // Show tips when mouse hovers ToolTip toolTip = new ToolTip(); toolTip.SetToolTip(buttonRecognize, "Select a file to recognize"); toolTip.SetToolTip(buttonRecord, "Record/Stop audio"); toolTip.SetToolTip(buttonRead, "Start reading"); toolTip.SetToolTip(buttonReadPause, "Pause reading"); toolTip.SetToolTip(buttonReadStop, "Stop reading"); toolTip.SetToolTip(textBoxFile, "Click to select a audio file"); toolTip.SetToolTip(comboBoxLan, "Select the target language"); toolTip.SetToolTip(richTextBoxResult, "Recognition text or Text to be Read"); }
public static string checkAudio(string fileName) { WavInfo wav = ClassUtils.GetWavInfo(fileName); //数据量 = (采样频率 × 采样位数 × 声道数 × 时间) / 8 // 非8k/16k, 16bit 位深, 单声道的,进行格式转换 if (fileName.EndsWith(".mp3", StringComparison.CurrentCultureIgnoreCase) || int.Parse(wav.dwsamplespersec.ToString()) != 16000 || int.Parse(wav.wbitspersample.ToString()) != 16 || int.Parse(wav.wchannels.ToString()) != 1) { fileName = ClassUtils.Convert2Wav(fileName); // convert audio file to 16k,16bit wav } return(fileName); }