


C++ calls Microsoft's own speech recognition interface to get started quickly
Quick Start with C++ Speech Recognition Interface (Microsoft Speech SDK)
I recently used Microsoft’s C++ speech recognition interface in my graduation project and searched a lot I also encountered many problems with the materials and took many detours. Now I write down my own experience, one is to improve myself, and the other is to repay the society. I hope that after reading this blog, you will learn how to implement the C++ speech recognition interface in 5 minutes. (The platform used is win8+VS2013)
1. Install SDK
Install MicrosoftSpeechPlatformSDK.msi, just install it to the default path.
Download path:
download.csdn.net/detail/michaelliang12/9510691
2. Create a new project and configure the environment
Settings:
1, Properties – Configuration properties –C/C++–General–Additional include directory: C:\Program Files\Microsoft SDKs\Speech\v11.0\Include (the specific path is related to the installation path)
2, Properties – Configuration Properties – Linker – Input – Additional dependencies: sapi.lib;
3. Speech recognition code
The speech recognition interface can be divided into text-to-speech and speech-to-text
1. Text-to-speech
Header files that need to be added:
#include <sapi.h> //导入语音头文件#pragma comment(lib,"sapi.lib") //导入语音头文件库
Function:
void CBodyBasics::MSSSpeak(LPCTSTR speakContent)// speakContent为LPCTSTR型的字符串,调用此函数即可将文字转为语音{ ISpVoice *pVoice = NULL; //初始化COM接口 if (FAILED(::CoInitialize(NULL))) MessageBox(NULL, (LPCWSTR)L"COM接口初始化失败!", (LPCWSTR)L"提示", MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2); //获取SpVoice接口 HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void**)&pVoice); if (SUCCEEDED(hr)) { pVoice->SetVolume((USHORT)100); //设置音量,范围是 0 -100 pVoice->SetRate(2); //设置速度,范围是 -10 - 10 hr = pVoice->Speak(speakContent, 0, NULL); pVoice->Release(); pVoice = NULL; } //释放com资源 ::CoUninitialize(); }
2. Voice to text
This is a little more troublesome because it requires real-time monitoring of the microphone, which involves to the messaging mechanism of Windows.
(1) First set the project properties:
Properties – Configuration Properties – C/C++ – Preprocessor – Preprocessor Definition: _WIN32_DCOM;
(2) Header files that need to be added:
#include <sapi.h> //导入语音头文件#pragma comment(lib,"sapi.lib") //导入语音头文件库#include//语音识别头文件#include //要用到CString#pragma onceconst int WM_RECORD = WM_USER + 100;//定义消息
(3) Define variables in the .h header file of the program
//定义变量CComPtr<ISpRecognizer>m_cpRecoEngine;// 语音识别引擎(recognition)的接口。CComPtr<ISpRecoContext>m_cpRecoCtxt;// 识别引擎上下文(context)的接口。CComPtr<ISpRecoGrammar>m_cpCmdGrammar;// 识别文法(grammar)的接口。CComPtr<ISpStream>m_cpInputStream;// 流()的接口。CComPtr<ISpObjectToken>m_cpToken;// 语音特征的(token)接口。CComPtr<ISpAudio>m_cpAudio;// 音频(Audio)的接口。(用来保存原来默认的输入流)ULONGLONG ullGrammerID;
(4) Create a speech recognition initialization function (called when the program just starts executing, for example, in the example code at the end of the article, This initialization function is placed in the response code of the dialog box initialization message WM_INITDIALOG)
//语音识别初始化函数void CBodyBasics::MSSListen() { //初始化COM接口 if (FAILED(::CoInitialize(NULL))) MessageBox(NULL, (LPCWSTR)L"COM接口初始化失败!", (LPCWSTR)L"提示", MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2); HRESULT hr = m_cpRecoEngine.CoCreateInstance(CLSID_SpSharedRecognizer);//创建Share型识别引擎 if (SUCCEEDED(hr)) { hr = m_cpRecoEngine->CreateRecoContext(&m_cpRecoCtxt);//创建识别上下文接口 hr = m_cpRecoCtxt->SetNotifyWindowMessage(m_hWnd, WM_RECORD, 0, 0);//设置识别消息 const ULONGLONG ullInterest = SPFEI(SPEI_SOUND_START) | SPFEI(SPEI_SOUND_END) | SPFEI(SPEI_RECOGNITION);//设置我们感兴趣的事件 hr = m_cpRecoCtxt->SetInterest(ullInterest, ullInterest); hr = SpCreateDefaultObjectFromCategoryId(SPCAT_AUDIOIN, &m_cpAudio); m_cpRecoEngine->SetInput(m_cpAudio, true); //创建语法规则 //dictation听说式 //hr = m_cpRecoCtxt->CreateGrammar(GIDDICTATION, &m_cpDictationGrammar); //if (SUCCEEDED(hr)) //{ // hr = m_cpDictationGrammar->LoadDictation(NULL, SPLO_STATIC);//加载词典 //} //C&C命令式,此时语法文件使用xml格式 ullGrammerID = 1000; hr = m_cpRecoCtxt->CreateGrammar(ullGrammerID, &m_cpCmdGrammar); WCHAR wszXMLFile[20] = L"";//加载语法 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)"CmdCtrl.xml", -1, wszXMLFile, 256);//ANSI转UNINCODE hr = m_cpCmdGrammar->LoadCmdFromFile(wszXMLFile, SPLO_DYNAMIC); //MessageBox(NULL, (LPCWSTR)L"语音识别已启动!", (LPCWSTR)L"提示", MB_CANCELTRYCONTINUE ); //激活语法进行识别 //hr = m_cpDictationGrammar->SetDictationState(SPRS_ACTIVE);//dictation hr = m_cpCmdGrammar->SetRuleState(NULL, NULL, SPRS_ACTIVE);//C&C hr = m_cpRecoEngine->SetRecoState(SPRST_ACTIVE); } else { MessageBox(NULL, (LPCWSTR)L"语音识别引擎启动出错!", (LPCWSTR)L"警告", MB_OK); exit(0); } //释放com资源 ::CoUninitialize(); //hr = m_cpCmdGrammar->SetRuleState(NULL, NULL, SPRS_INACTIVE);//C&C}
(5) Define the message processing function
needs to be placed together with other message processing codes, such as in the code of this article, placed The end of the DlgProc() function of the sample code at the end of the article. The entire other code blocks in this article can be copied directly. You only need to change the following Message response module
//消息处理函数USES_CONVERSION; CSpEvent event; if (m_cpRecoCtxt) { while (event.GetFrom(m_cpRecoCtxt) == S_OK){ switch (event.eEventId) { case SPEI_RECOGNITION: { //识别出了语音 m_bGotReco = TRUE; static const WCHAR wszUnrecognized[] = L"<Unrecognized>"; CSpDynamicString dstrText; ////取得识别结果 if (FAILED(event.RecoResult()->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &dstrText, NULL))) { dstrText = wszUnrecognized; } BSTR SRout; dstrText.CopyToBSTR(&SRout); CString Recstring; Recstring.Empty(); Recstring = SRout; //做出反应(*****消息反应模块*****) if (Recstring == "发短信") { //MessageBox(NULL, (LPCWSTR)L"好的", (LPCWSTR)L"提示", MB_OK); MSSSpeak(LPCTSTR(_T("好,马上发短信!"))); } else if (Recstring == "李雷") { MSSSpeak(LPCTSTR(_T("好久没看见他了,真是 long time no see"))); } } break; } } }
(6) Modify the syntax file
Modify the CmdCtrl.xml file, you can Improve the recognition of certain words, and the recognition effect of the words inside will be much better, such as people's names, etc. (In addition, when running the exe alone, you also need to put this file in the same folder as the exe. If you do not put it, no error will be reported, but the vocabulary recognition effect in the grammar file will become worse)
<?xml version="1.0" encoding="utf-8"?><GRAMMAR LANGID="804"> <DEFINE> <ID NAME="VID_SubName1" VAL="4001"/> <ID NAME="VID_SubName2" VAL="4002"/> <ID NAME="VID_SubName3" VAL="4003"/> <ID NAME="VID_SubName4" VAL="4004"/> <ID NAME="VID_SubName5" VAL="4005"/> <ID NAME="VID_SubName6" VAL="4006"/> <ID NAME="VID_SubName7" VAL="4007"/> <ID NAME="VID_SubName8" VAL="4008"/> <ID NAME="VID_SubName9" VAL="4009"/> <ID NAME="VID_SubNameRule" VAL="3001"/> <ID NAME="VID_TopLevelRule" VAL="3000"/> </DEFINE> <RULE ID="VID_TopLevelRule" TOPLEVEL="ACTIVE"> <O> <L> <P>我要</P> <P>运行</P> <P>执行</P> </L> </O> <RULEREF REFID="VID_SubNameRule" /> </RULE> <RULE ID="VID_SubNameRule" > <L PROPID="VID_SubNameRule"> <P VAL="VID_SubName1">发短信</P> <P VAL="VID_SubName2">是的</P> <P VAL="VID_SubName3">好的</P> <P VAL="VID_SubName4">不用</P> <P VAL="VID_SubName5">李雷</P> <P VAL="VID_SubName6">韩梅梅</P> <P VAL="VID_SubName7">中文界面</P> <P VAL="VID_SubName8">英文界面</P> <P VAL="VID_SubName9">English</P> </L> </RULE></GRAMMAR>
The above is the detailed content of C++ calls Microsoft's own speech recognition interface to get started quickly. For more information, please follow other related articles on the PHP Chinese website!

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.