科大訊飛語音接口-iat語音聽寫
Demo下載下傳連結:
https://download.csdn.net/download/jinglell/11566402

首先,來看科大訊飛給的msc.dll API文檔,
可以看到給出了語音識别詳細的接口說明,
http://mscdoc.xfyun.cn/windows/api/iFlytekMSCReferenceManual/qisr_8h.html
然後我們看另一個文檔
http://mscdoc.xfyun.cn/windows/api/iFlytekMSCReferenceManual/msp__cmn_8h.html
這裡面就包含了MSC的初始化登入與最後的登出。
接下來就是引入MSC裡面的接口,使用DLLImport(),我将DLL的import單獨放在了一個檔案裡。
之後就是編寫audio2text.ashx請求頁,
首先要對appID進行修改,修改你自己的,并将msc.dll替換為你自己從官網下載下傳來的,以免版本不同出現問題(若是遇到找不到某個msc.dll裡的方法,請先到上面的MSCAPI文檔裡找原因)
private static string audio_iat(string audio_path, string session_begin_params)
{
if (audio_path == null || audio_path == "") return "";
IntPtr session_id;
StringBuilder result = new StringBuilder();//存儲最終識别的結果
var aud_stat = AudioStatus.MSP_AUDIO_SAMPLE_CONTINUE;//音頻狀态
var ep_stat = EpStatus.MSP_EP_LOOKING_FOR_SPEECH;//端點狀态
var rec_stat = RecogStatus.MSP_REC_STATUS_SUCCESS;//識别狀态
int errcode = (int)Errors.MSP_SUCCESS;
byte[] audio_content; //用來存儲音頻檔案的二進制資料
int totalLength = 0;//用來記錄總的識别後的結果的長度,判斷是否超過緩存最大值
try
{
audio_content = File.ReadAllBytes(audio_path);
//SoundPlayer player = new SoundPlayer(audio_path);
//player.Play();
}
catch (Exception e)
{
//Console.WriteLine(e);
System.Diagnostics.Debug.WriteLine(e.Message);
audio_content = null;
}
try
{
if (audio_content == null)
throw new Exception("沒有讀取到任何内容");
//Console.WriteLine("開始進行語音聽寫.......");
session_id = mscDLL.QISRSessionBegin(null, session_begin_params, ref errcode);
if (errcode != (int)Errors.MSP_SUCCESS)
throw new Exception("開始一次語音識别失敗!");
int res = mscDLL.QISRAudioWrite(session_id, audio_content, (uint)audio_content.Length, aud_stat, ref ep_stat, ref rec_stat);
if (res != (int)Errors.MSP_SUCCESS)
throw new Exception("寫入識别的音頻失敗!" + res);
res = mscDLL.QISRAudioWrite(session_id, null, 0, AudioStatus.MSP_AUDIO_SAMPLE_LAST, ref ep_stat, ref rec_stat);
if (res != (int)Errors.MSP_SUCCESS)
new Exception("寫入音頻失敗!" + res);
while (RecogStatus.MSP_REC_STATUS_COMPLETE != rec_stat)
{
IntPtr now_result = mscDLL.QISRGetResult(session_id, ref rec_stat, 0, ref errcode);
if (errcode != (int)Errors.MSP_SUCCESS)
throw new Exception("擷取結果失敗:" + errcode);
if (now_result != null)
{
int length = now_result.ToString().Length;
totalLength += length;
if (totalLength > 4096)
throw new Exception("緩存空間不夠" + totalLength);
result.Append(Marshal.PtrToStringAnsi(now_result));
}
Thread.Sleep(150);//防止頻繁占用cpu
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
finally
{
//Console.WriteLine("語音聽寫結束");
//Console.WriteLine("聽寫結果: ");
//Console.WriteLine(result);
//int res = mscDLL.MSPLogout();//使用者名,密碼,登陸資訊,前兩個均為空
}
return result.ToString();
}
而這時其實已經可以對官方提供的.wav測試樣例進行識别了,但是我們平時若是有其他系統對接我們的接口時,比如我這次的微信小程式,會發現通過錄音得來的是.mp3音頻格式,科大訊飛要求的卻是.wav/.pcm格式,該怎麼轉換音頻格式?
見下一篇文章:
微信小程式+.NET(五) 音頻格式轉換:
https://blog.csdn.net/jinglell/article/details/99677371