From Free Pascal wiki
Revision as of 12:04, 29 September 2021 by Trev (talk | contribs) (Add See also section)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search


SAPI stands for Speech Application Programming Interface, a Microsoft Windows API used to perform text-to-speech (TTS).

Use with Free Pascal

Lazarus / Free Pascal can use this interface to perform TTS. Source: forum post: [1]

On Windows Vista and above, you will run in trouble with the FPU interrupt mask (see [2]). The code dealing with SavedCW is meant to work around this.

  SavedCW: Word;
  SpVoice: Variant;
  SpVoice := CreateOleObject('SAPI.SpVoice');
  // Change FPU interrupt mask to avoid SIGFPE exceptions
  SavedCW := Get8087CW;
    Set8087CW(SavedCW or $4);
    SpVoice.Speak('hi', 0);
    // Restore FPU mask

For the options available with SpVoice.Speak and other SpVoice methods see


Warning: The OLE object created in above snippet will be destroyed automatically when the SpVoice variant goes out of scope. For larger texts the use of the asynchronous mode allows to keep your application reactive while speak is running. In that case it is especially important to control carefully the lifetime of the object and store it in a global or class variable. Destroying the object while speak is still running can cause crashes.

Changing the FPU interrupt mask can be done at any moment before loading the ole object and if your application is not using any floating point arithmetic there is no need to reset the FPU interrupt mask to its original value.

Assigning text to a variable. A WideString must used

File:procedure TForm1.Button1Click(Sender: TObject);
  SpVoice1: Variant;
  VoiceString: WideString; // WideString must be used to assign variable for speech to function, can be Global.
  SpVoice1 := CreateOleObject('SAPI.SpVoice'); // Can be assigned in form.create
  VoiceString := Button1.Caption;              // variable assignment 

Thank you nsunny from 2013 post.


See the Speech Synthesis article.

See also