views:

163

answers:

1

I am trying to convert text to wave file using following function. It works fine if called from main UI thread. But it fails when calling from another thread. How to call it from a multi-threaded function?

void Pan_Channel::TextToPlaybackFile( CString Text, CString FileName )
{
 // Result variable
 HRESULT Result = S_OK;

 // Voice Object
 CComPtr<ISpVoice> cpVoice;

 // Create a SAPI Voice
 Result = cpVoice.CoCreateInstance( CLSID_SpVoice );

 // Audio format
 CSpStreamFormat cAudioFmt;

 // Set the audio format
 if( SUCCEEDED( Result ) )
 {
  Result = cAudioFmt.AssignFormat( SPSF_8kHz16BitMono );
 }

 // File Stream
 CComPtr<ISpStream> cpStream;

 // Call SPBindToFile, a SAPI helper method,  to bind the audio stream to the file
 if( SUCCEEDED( Result ) )
 {
  Result = SPBindToFile( FileName, SPFM_CREATE_ALWAYS, &cpStream,
   &cAudioFmt.FormatId(), cAudioFmt.WaveFormatExPtr() );
 }

 // set the output to cpStream so that the output audio data will be stored in cpStream
 if( SUCCEEDED( Result ) )
 {
  Result = cpVoice->SetOutput( cpStream, TRUE );
 }

  // Speak the text syncronously
 if( SUCCEEDED( Result ) )
 {
  Result = cpVoice->Speak( Text.AllocSysString(), SPF_DEFAULT, NULL );
 }

 // close the stream
 if( SUCCEEDED( Result ) )
 {
  Result = cpStream->Close();
 }

 // Release stream
 cpStream.Release();

 // Release voice object
 cpVoice.Release();
}
+2  A: 

Have you CoInitialized the other thread? COM needs to be initialized on each thread using it. Also .. do you use a COM object created in one thread in another thread? Because you need to marshall the interface between threads if you do that ...

Goz
Many thanks for your reply. I forgot to call CoInitialize() and CoUninitialize() which caused the problem. Now it is working after adding proper initialization calls. Can you please tell me why the same function worked when called from main UI thread even without call to CoInitialize()?
Vadakkumpadath
Probably because something ELSE called CoInitialize on the main thread. MFC initialisation perhaps?
Goz