C# 实现语音听写

本文系原创,禁止转载。

分享如何使用c#对接科大讯飞语音听写服务,简单高效地实现语音听写。

实现语音听写主要分为录音和语音识别两部分;录音是指获取设备声卡端口的音频数据并将之保存为音频文件,语音识别就是将刚才所述的音频文件通过调用讯飞的语音听写服务转换为文字。

相关的类库文件

1. 开源录音库 NAudio.dll 

  http://pan.baidu.com/s/1dFth2nv

2.语音听写库 msc.dll

  去讯飞开放平台申请相关的SDK

录音部分可以使用开源的.net音频处理类库NAudio.dll,它是托管的类库,使用起来比较方便,当然你也可以自己去读声卡录音,微软有相关的系统API,这里不详述。

录音部分核心代码:

 1 //初始化
 2             String FilePath = AppDomain.CurrentDomain.BaseDirectory + "Temp.wav";
 3             WaveIn m_waveSource = new WaveIn();
 4             m_waveSource.WaveFormat = new NAudio.Wave.WaveFormat(16000, 16, 1);// 16bit,16KHz,Mono的录音格式
 5             m_waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
 6             m_waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);
 7             WaveFileWriter m_waveFile = new WaveFileWriter(m_fileName, m_waveSource.WaveFormat);
 8             
 9             //开始录音
10             m_waveSource.StartRecording();
11             
12             //保存到截获到的声音
13             private void waveSource_DataAvailable(object sender, WaveInEventArgs e)
14           {
15             if (m_waveFile != null)
16             {
17                 m_waveFile.Write(e.Buffer, 0, e.BytesRecorded);
18                 m_waveFile.Flush();
19             }
20           }
21         
22           //停止录音
23           m_waveSource.StopRecording();

录音完成后就可以进行语音听写了,讯飞提供的语音听写服务SDK中的类库msc.dll是原生的类库,在c#中没有办法像托管类库那样使用,需要通过使用Import的方式来引用,也可以包装成托管的类库来使用,这里只介绍第一种方法。

上述类库是msc.dll使用C语言封装的,在声明接口的时候需注意C语言的变量类型的表达方式与C#有很多不同之处;比如,在SDK中有很多针对内存地址操作的,所以涉及到很多的指针类型变量,而C#中指针概念相对较弱。提供两个解决思路,一是在C#中声明UnSafe代码,这样就可以像C/C++一样使用指针,二是使用IntPtr、ref 变量的表达方式,来实现“兼容”。
相关接口声明:

 1      [DllImport("msc.dll", CallingConvention = CallingConvention.StdCall)]
 2         public static extern int MSPLogin(string usr, string pwd, string @params);
 3 
 4         [DllImport("msc.dll", CallingConvention = CallingConvention.StdCall)]
 5         public static extern IntPtr QISRSessionBegin(string grammarList, string _params, ref int errorCode);
 6 
 7         [DllImport("msc.dll", CallingConvention = CallingConvention.StdCall)]
 8         public static extern int QISRGrammarActivate(string sessionID, string grammar, string type, int weight);
 9 
10         [DllImport("msc.dll", CallingConvention = CallingConvention.StdCall)]
11         public static extern int QISRAudioWrite(string sessionID, IntPtr waveData, uint waveLen, int audioStatus, ref int epStatus, ref int recogStatus);
12 
13         [DllImport("msc.dll", CallingConvention = CallingConvention.StdCall)]
14         public static extern IntPtr QISRGetResult(string sessionID, ref int rsltStatus, int waitTime, ref int errorCode);
15 
16         [DllImport("msc.dll", CallingConvention = CallingConvention.StdCall)]
17         public static extern int QISRSessionEnd(string sessionID, string hints);
18 
19         [DllImport("msc.dll", CallingConvention = CallingConvention.StdCall)]
20         public static extern int QISRGetParam(string sessionID, string paramName, string paramValue, ref uint valueLen);
21 
22         [DllImport("msc.dll", CallingConvention = CallingConvention.StdCall)]
23         public static extern int MSPLogout();

业务流程:
1.调用 MSPLogin(...)接口登入,可以只登入一次,但是必须保证在调用其他接口前先登入;
2.调用 QISRSessionBegin(...)开始一次语音听写;
3.调用 QISRAudioWrite(...) 分块写入音频数据
4.循环调用 QISRGetResult(...) 接口返回听写结果
5.调用 QISRSessionEnd(...) 主动结束本次听写
6.不再使用服务的时候 调用MSPLogout()登出,避免不必要的麻烦。
核心代码:

public string AudioToString(string inFile)
        {
            int ret = 0;
            string text = String.Empty;
            FileStream fileStream = new FileStream(inFile, FileMode.OpenOrCreate);
            byte[] array = new byte[this.BUFFER_NUM];
            IntPtr intPtr = Marshal.AllocHGlobal(this.BUFFER_NUM);
            int audioStatus = 2;
            int epStatus = -1;
            int recogStatus = -1;
            int rsltStatus = -1;
            while (fileStream.Position != fileStream.Length)
            {
                int waveLen = fileStream.Read(array, 0, this.BUFFER_NUM);
                Marshal.Copy(array, 0, intPtr, array.Length);
                ret = iFlyASR.QISRAudioWrite(this.m_sessionID, intPtr, (uint)waveLen, audioStatus, ref epStatus, ref recogStatus);
                if (ret != 0)
                {
                    fileStream.Close();
                    throw new Exception("QISRAudioWrite err,errCode=" + ret);
                }
                if (recogStatus == 0)
                {
                    IntPtr intPtr2 = iFlyASR.QISRGetResult(this.m_sessionID, ref rsltStatus, 0, ref ret);
                    if (intPtr2 != IntPtr.Zero)
                    {
                        text += this.Ptr2Str(intPtr2);
                    }
                }
                Thread.Sleep(500);
            }
            fileStream.Close();
            audioStatus = 4;
            ret = iFlyASR.QISRAudioWrite(this.m_sessionID, intPtr, 1u, audioStatus, ref epStatus, ref recogStatus);
            if (ret != 0)
            {
                throw new Exception("QISRAudioWrite write last audio err,errCode=" + ret);
            }
            int timesCount = 0;
            while (true)
            {
                IntPtr intPtr2 = iFlyASR.QISRGetResult(this.m_sessionID, ref rsltStatus, 0, ref ret);
                if (intPtr2 != IntPtr.Zero)
                {
                    text += this.Ptr2Str(intPtr2);
                }
                if (ret != 0)
                {
                    break;
                }
                Thread.Sleep(200);
                if (rsltStatus == 5 || timesCount++ >= 50)
                {
                    break;
                }
            }
            return text;
        }

自己设计以下UI交互,或者和你的应用程序结合一下,就可以让你的应用程序长一双会听的耳朵了!

结果:

 

posted @ 2017-07-21 16:09  王小豆又叫小王子  阅读(5633)  评论(19编辑  收藏  举报