利用SAPI对WAV文件进行语音识别

 
void VoiceRecognition(void)
{
 CComPtr<ISpStream>   cpInputStream;
 CComPtr<ISpRecognizer>  cpRecognizer;
 CComPtr<ISpRecoContext>  cpRecoContext;
 CComPtr<ISpRecoGrammar>  cpGrammar;
 CComPtr<ISpVoice>   cpVoice;
 CComPtr<ISpStream>   m_cpSpStream; 
 HRESULT hr;
 hr = E_FAIL;
 if (SUCCEEDED(hr = ::CoInitialize(NULL)))
 {
  {
   //创建识别引擎
   hr = cpRecognizer.CoCreateInstance(CLSID_SpInprocRecognizer);
   if(FAILED(hr)){printf("Recognizer Create failed");}
   if(SUCCEEDED(hr))
   {hr = cpRecognizer->CreateRecoContext( &cpRecoContext );}
   //WIN32
   if (SUCCEEDED(hr))
   {hr = cpRecoContext->SetNotifyWin32Event();}
   //interest
   if (SUCCEEDED(hr))
   {const ULONGLONG ullInterest = SPFEI(SPEI_RECOGNITION);
    hr = cpRecoContext->SetInterest(ullInterest, ullInterest);} 
   BSTR bstrFile = SysAllocString(OLESTR("C:\\1.wav"));
   SPBindToFile(bstrFile,SPFM_OPEN_READONLY ,&m_cpSpStream);
   // set the input for the engine
   hr = cpRecognizer->SetInput(m_cpSpStream, TRUE);
   hr = cpRecognizer->SetRecoState( SPRST_ACTIVE );
   if (SUCCEEDED(hr))
   {hr = cpRecoContext->CreateGrammar( 0, &cpGrammar );}
   if  (SUCCEEDED(hr))
   {hr = cpGrammar->LoadDictation(NULL, SPLO_STATIC);}
   if (SUCCEEDED(hr))
   {hr = cpGrammar->SetDictationState( SPRS_ACTIVE );}
   if (SUCCEEDED(hr))
   {
    USES_CONVERSION;
//    const WCHAR * const pchStop = StopWord();
    CComPtr<ISpRecoResult> cpResult;
    if (SUCCEEDED(hr = BlockForResult(cpRecoContext, &cpResult)))
    {
     cpGrammar->SetDictationState( SPRS_INACTIVE );
     CSpDynamicString dstrText;
     if (SUCCEEDED(cpResult->GetText((ULONG)SP_GETWHOLEPHRASE, (ULONG)SP_GETWHOLEPHRASE,TRUE, &dstrText, NULL)))
     {
      //printf("Recognition Result:  %s\n", W2A(dstrText));
      //MessageBox(NULL,dstrText+5,TEXT("识别结果"),MB_OK);
      string temp_str;
      WCharToMByte((dstrText+5), temp_str); 
      strColumn=temp_str;
      cpResult.Release();
     }
     cpGrammar->SetDictationState( SPRS_ACTIVE );
    }
   }
  }
  ::CoUninitialize();
 }
}
 
 

你可能感兴趣的:(利用SAPI对WAV文件进行语音识别)