Speech synthesis: Difference between revisions

m
No edit summary
m (→‎{{header|Wren}}: Minor tidy)
 
(39 intermediate revisions by 25 users not shown)
Line 4:
[[Category:Temporal media]]
 
Render the text &nbsp; “<tt>&nbsp; &nbsp; '''This is an example of speech synthesis</tt>”'''&nbsp; &nbsp; &nbsp; as speech.
 
 
;Related task:
:* &nbsp; [[Using_a_Speech_engine_to_highlight_words|using a speech engine to highlight words]]
<br><br>
 
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">os:(‘espeak 'Hello world!'’)</syntaxhighlight>
 
=={{header|AmigaBASIC}}==
 
<syntaxhighlight lang="amigabasic">text$=TRANSLATE$("This is an example of speech synthesis.")
SAY text$</syntaxhighlight>
 
=={{header|AppleScript}}==
Probably the only language where output to console is harder than output to a sound device.
<syntaxhighlight lang="applescript">
say "This is an example of speech synthesis"
</syntaxhighlight>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
 
<langsyntaxhighlight lang="ahk">talk := ComObjCreate("sapi.spvoice")
talk.Speak("This is an example of speech synthesis.")</langsyntaxhighlight>
 
=={{header|AutoIt}}==
 
<syntaxhighlight lang="autoit">$voice = ObjCreate("SAPI.SpVoice")
$voice.Speak("This is an example of speech synthesis.")</syntaxhighlight>
 
=={{header|BASIC256}}==
 
<langsyntaxhighlight BASIC256lang="basic256">say "Goodbye, World for the " + 123456 + "th time."
say "This is an example of speech synthesis."</langsyntaxhighlight>
 
=={{header|Batch File}}==
Sorry for cheating. This is Batch/JScript hybrid.
<syntaxhighlight lang="dos">@set @dummy=0 /*
::Batch File section
@echo off
cscript //e:jscript //nologo "%~f0" "%~1"
exit /b
::*/
//The JScript section
var objVoice = new ActiveXObject("SAPI.SpVoice");
objVoice.speak(WScript.Arguments(0));</syntaxhighlight>
{{Out}}
Saved as SPEAK.BAT
<pre>>SPEAK "This is an example of speech synthesis"
 
></pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
This calls the SAPI5 API directly, it does not need an external program.
<langsyntaxhighlight lang="bbcbasic"> SPF_ASYNC = 1
ON ERROR SYS `CoUninitialize` : PRINT 'REPORT$ : END
ON CLOSE SYS `CoUninitialize` : QUIT
Line 59 ⟶ 102:
DEF PROC_voice_free(V%)
SYS !(!V%+8), V%
ENDPROC</langsyntaxhighlight>
 
=={{header|Batch File}}==
Sorry for cheating. This is Batch/JScript hybrid.
<lang dos>@set @dummy=0 /*
::Batch File section
@echo off
cscript //e:jscript //nologo "%~f0" "%~1"
exit /b
::*/
//The JScript section
var objVoice = new ActiveXObject("SAPI.SpVoice");
objVoice.speak(WScript.Arguments(0));</lang>
{{Out}}
Saved as SPEAK.BAT
<pre>>SPEAK "This is an example of speech synthesis"
 
></pre>
 
=={{header|C}}==
Line 82 ⟶ 108:
 
{{libheader|POSIX}}
<langsyntaxhighlight lang="c">#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
Line 113 ⟶ 139:
talk("This is an example of speech synthesis.");
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
You need to 'Add Reference' to the COM "Microsoft Speech Object Library" in your Preferences.
<langsyntaxhighlight lang="csharp">using SpeechLib;
 
namespace Speaking_Computer
Line 129 ⟶ 155:
}
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
{{libheader|facts/speech-synthesis}}
<langsyntaxhighlight lang="clojure">(use 'speech-synthesis.say)
(say "This is an example of speech synthesis.")</langsyntaxhighlight>
 
 
=={{header|FreeBASIC}}==
FreeBASIC does not have a native command for them.
 
We are going to invoke vbscript directly
<syntaxhighlight lang="freebasic">''This works on Windows. Does anyone know how it would be done in Linux?
 
Sub speak(texto As String)
Dim As String frase
frase ="mshta vbscript:Execute(""CreateObject(""""SAPI.SpVoice"""").Speak("""""+texto+""""")(window.close)"")"
Print texto
Shell frase
End Sub
 
speak "Vamos a contar " + str(123456)
speak "This is an example of speech synthesis."
Sleep</syntaxhighlight>
 
 
=={{header|FutureBasic}}==
FB offers easy access to excellent quality native synthesized voices in a variety of accents and languages available on Macs as demonstrated here. For a more comprehensive demonstration of speech synthesis, see the FutureBasic Rosetta Code task solution to: [[https://rosettacode.org/wiki/Old_lady_swallowed_a_fly#FutureBasic|FB's Old Laday Swallowed a Fly.]]
<syntaxhighlight lang="futurebasic">
 
SpeechSynthesizerRef ref
ref = fn SpeechSynthesizerWithVoice( @"com.apple.speech.synthesis.voice.daniel.premium" )
fn SpeechSynthesizerStartSpeakingString( ref, @"This is an example of speech synthesis." )
 
HandleEvents
</syntaxhighlight>
 
=={{header|GlovePIE}}==
<syntaxhighlight lang="glovepie">if var.number=0 then
var.number=1
say("This is an example of speech synthesis.")
endif</syntaxhighlight>
 
=={{header|Go}}==
Here's a library solution, but using a library written from scratch in Go.
<langsyntaxhighlight lang="go">package main
 
import (
Line 165 ⟶ 227:
synthesized := gospeech.DefaultVoice.Synthesize(phonetics)
wav.WriteFile(synthesized, "output.wav")
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Mac only:
<langsyntaxhighlight lang="groovy">'say "This is an example of speech synthesis."'.execute()</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">
import System.Process (callProcess) -- From “process” library
import System
 
say xtext = system $callProcess "espeak" ["--", ++ show xtext]
 
main = say "This is an example of speech synthesis."
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
This should work in most major browsers
{{works with|Javascript}}
<syntaxhighlight lang="javascript">
var utterance = new SpeechSynthesisUtterance("This is an example of speech synthesis.");
window.speechSynthesis.speak(utterance);
</syntaxhighlight>
 
Windows only:
{{works with|JScript}}
<langsyntaxhighlight lang="javascript">var voice = new ActiveXObject("SAPI.SpVoice");
voice.speak("This is an example of speech synthesis.");</langsyntaxhighlight>
 
=={{header|Julia}}==
It seems that this and similar tasks can reduce to how the language can call an external program. Using the Julia REPL:
<syntaxhighlight lang="julia">
julia> a = "hello world"
"hello world"
 
julia> run(`espeak $a`)
</syntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|C}}
{{works with|Ubuntu 16.04}}
Note that this code does not work on Windows 10.
 
Note also that Kotlin Native does not support the automatic translation of C function-like macros such as WIFEXITED and WEXITSTATUS.
 
Whilst it is often possible to wrap such macros in 'ordinary' C functions and then expose the latter to Kotlin via a .klib, it is not worth the effort here. I have therefore confined myself to simply reporting a non-zero error status.
 
<syntaxhighlight lang="scala">// Kotlin Native v0.6.2
 
import kotlinx.cinterop.*
import platform.posix.*
 
fun talk(s: String) {
val pid = fork()
if (pid < 0) {
perror("fork")
exit(1)
}
if (pid == 0) {
execlp("espeak", "espeak", s, null)
perror("espeak")
_exit(1)
}
memScoped {
val status = alloc<IntVar>()
waitpid(pid, status.ptr, 0)
if (status.value > 0) println("Exit status was ${status.value}")
}
}
 
fun main(args: Array<String>) {
talk("This is an example of speech synthesis.")
}</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
Assumes that 'espeak' is available at the path shown.
<syntaxhighlight lang="lb">
<lang lb>
nomainwin
run "C:\Program Files\eSpeak\command_line\espeak "; chr$( 34); "This is an example of speech synthesis."; chr$( 34)
end
</langsyntaxhighlight>
Another dll has been posted to do the same job, at [http://basic.wikispaces.com/SpeechLibrary LB Community Wiki]
 
Line 198 ⟶ 313:
Both hardware and software-only speech synthesizers exist for the CPC. A software-only solution, [http://www.cpc-power.com/index.php?page=detail&num=4372 Speech 1.1] by Superior Software (1986), supplies three BASIC extension commands (RSXes), "|say", "|speak", and "|pitch":
 
<langsyntaxhighlight lang="locobasic">|say,"This is an example of speech synthesis."</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
For Linux, through wine, if missing Sapi5 need this: winetricks speechsdk
 
 
===Using Statement Speech===
<syntaxhighlight lang="m2000 interpreter">
Module UsingStatementSpeech {
Volume 100
Speech "This is an example of speech synthesis."
}
UsingStatementSpeech
</syntaxhighlight>
===Print each word as speak===
<syntaxhighlight lang="m2000 interpreter">
Module UsingEvents {
Declare WithEvents sp "SAPI.SpVoice"
That$="This is an example of speech synthesis."
EndStream=False
Function sp_Word {
Read New StreamNumber, StreamPosition, CharacterPosition, Length
Rem: Print StreamNumber, StreamPosition, CharacterPosition, Length
Print Mid$(That$, CharacterPosition+1, Length);" ";
Refresh
}
Function sp_EndStream {
Print
Refresh
EndStream=True
}
Const SVEStartInputStream = 2
Const SVEEndInputStream = 4
Const SVEVoiceChange = 8
Const SVEBookmark = 16
Const SVEWordBoundary = 32
Const SVEPhoneme = 64
Const SVESentenceBoundary = 128
Const SVEViseme = 256
Const SVEAudioLevel = 512
Const SVEPrivate = 32768
Const SVEAllEvents = 33790
Const SVSFDefault = 0&
Const SVSFlagsAsync = 1&
Const SVSFPurgeBeforeSpeak=2&
With sp, "EventInterests", SVEWordBoundary+SVEEndInputStream
Method sp, "Speak", That$, SVSFlagsAsync
While Not EndStream {Wait 10}
}
UsingEvents
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Speak["This is an example of speech synthesis."]</syntaxhighlight>
 
=={{header|Nim}}==
Using same method as Julia.
<syntaxhighlight lang="nim">import osproc
 
discard execCmd("espeak 'Hello world!'")</syntaxhighlight>
 
=={{header|PARI/GP}}==
 
Define a function that is using espeak package from Linux.
<syntaxhighlight lang="parigp">speak(txt,opt="")=extern(concat(["espeak ",opt," \"",txt,"\""]));</syntaxhighlight>
 
Now let it speak:
<syntaxhighlight lang="parigp">speak("This is an example of speech synthesis")</syntaxhighlight>
 
A monster speech tongue-twister:
<syntaxhighlight lang="parigp">speak("The seething sea ceaseth and thus the seething sea sufficeth us.","-p10 -s100")</syntaxhighlight>
 
A foreign language "Zungenbrecher":
=={{header|Mathematica}}==
<syntaxhighlight lang="parigp">speak("Fischers Fritz fischt frische Fische.","-vmb/mb-de2 -s130")</syntaxhighlight>
<lang Mathematica>Speak["This is an example of speech synthesis."]</lang>
 
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">use Speech::Synthesis;
 
($engine) = Speech::Synthesis->InstalledEngines();
Line 212 ⟶ 399:
Speech::Synthesis
->new(engine => $engine, voice => $voice->{id})
->speak("This is an example of speech synthesis.");</langsyntaxhighlight>
 
=={{header|Perl 6}}==
=={{header|Phix}}==
<lang perl6>run 'espeak', 'This is an example of speech synthesis.';</lang>
{{libheader|Phix/pGUI}}
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/Speak.htm here].
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Speak.exw
-- ======================
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- WINDOWS or JS, not LINUX</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #000000;">32</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Windows 32 bit only, for now...
-- (^ runs fine on a 64-bit OS, but needs a 32-bit p.exe)</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.2"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #7060A8;">speak</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> <span style="color: #000080;font-style:italic;">-- (new in 1.0.2)</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"This is an example of speech synthesis"</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">button_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">speak</span><span style="color: #0000FF;">(</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">btn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Speak"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"button_cb"</span><span style="color: #0000FF;">)),</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">btn</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"MARGIN=180x80"</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
Note that speech synthesis has refused to operate in a browser without user activation since 2018, hence the tiny GUI with a button.<br>
Should you for some strange reason want it on desktop/Phix without any GUI, you'd need to arrange for COM initialisation etc yourself.
 
=={{header|PHP}}==
 
Linux & Mac example uses eSpeak (eSpeak Instillation instructions included in comments).
Mac also has a built in Speech synthesis system and this example allows you to optionally use that instead of eSpeak.
Windows example uses built in Windows Speech API.
 
 
{{works with|Mac OS & Linux OS}}
<syntaxhighlight lang="php">
<?php
<?php
 
 
/*
_ _____ _ _ _ ___ __
| | |_ _| \ | | | | \ \ / /
| | | | | \| | | | |\ V /
| | | | | . ` | | | | > <
| |____ _| |_| |\ | |__| |/ . \
|______|_____|_| \_|\____//_/ \_\
*/
// Install eSpeak - Run this command in a terminal
/*
sudo apt-get install eSpeak
*/
 
 
/*
__ __ _____
| \/ | /\ / ____|
| \ / | / \ | |
| |\/| | / /\ \| |
| | | |/ ____ \ |____
|_| |_/_/ \_\_____|
*/
// Mac has it's own Speech Synthesis system
// accessible via the "say" command.
// To use eSpeak on a Mac, change this variable to true.
$mac_use_espeak = false;
 
// To use eSpeak on a Mac you need to install
// Homebrew Package Manager & eSpeak
// Run these commands in a terminal:
/*
 
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
 
brew install espeak
 
*/
 
$voice = "espeak";
$statement = 'Hello World!';
$save_file_args = '-w HelloWorld.wav'; // eSpeak args
 
// Ask PHP what OS it was compiled for,
// CAPITALIZE it and truncate to the first 3 chars.
$OS = strtoupper(substr(PHP_OS, 0, 3));
 
// If this is Darwin (MacOS) AND we don't want eSpeak
elseif($OS === 'DAR' && $mac_use_espeak == false) {
$voice = "say -v 'Victoria'";
$save_file_args = '-o HelloWorld.wav'; // say args
}
 
// Say It
exec("$voice '$statement'");
 
// Save it to a File
exec("$voice '$statement' $save_file_args");
</syntaxhighlight>
 
 
{{works with|Windows OS}}
<syntaxhighlight lang="php">
<?php
 
// List available SAPI voices
// 0 = Microsoft David Desktop - English (United States)
// 1 = Microsoft Zira Desktop - English (United States)
// ... If you have additional voices installed
function ListSAPIVoices(&$voice){
foreach($voice->GetVoices as $v){
echo $v->GetDescription . PHP_EOL;
}
}
 
 
 
$filename = "DaisyBell.wav";
 
// https://en.wikipedia.org/wiki/Daisy_Bell#Computing_and_technology
// "In 1961, an IBM 704 at Bell Labs was programmed to sing "Daisy Bell"-
// in the earliest demonstration of computer speech synthesis."
$statement = "There is a flower within my heart, Daisy, Daisy!
Planted one day by a glancing dart,
Planted by Daisy Bell!
Whether she loves me or loves me not,
Sometimes it's hard to tell;
Yet I am longing to share the lot
Of beautiful Daisy Bell!
 
Daisy, Daisy,
Give me your answer, do!
I'm half crazy,
All for the love of you!
It won't be a stylish marriage,
I can't afford a carriage,
But you'll look sweet on the seat
Of a bicycle built for two!
 
We will go tandem as man and wife, Daisy, Daisy!
Ped'ling away down the road of life, I and my Daisy Bell!
When the road's dark we can both despise Po'leaseman and lamps as well;
There are bright lights in the dazzling eyes Of beautiful Daisy Bell!
 
Daisy, Daisy,
Give me your answer, do!
I'm half crazy,
All for the love of you!
It won't be a stylish marriage,
I can't afford a carriage,
But you'll look sweet on the seat
Of a bicycle built for two!
 
I will stand by you in wheel or woe, Daisy, Daisy!
You'll be the bell which I'll ring you know! Sweet little Daisy Bell!
You'll take the lead in each trip we take, Then if I don't do well;
I will permit you to use the brake, My beautiful Daisy Bell!";
 
// COM (Component Object Model) objects
// https://www.php.net/manual/en/book.com.php
$voice = new COM("SAPI.SpVoice");
$voice_file_stream = new COM("SAPI.SpVoice");
$file_stream = new COM("SAPI.SpFileStream");
 
 
// Change $voice to Zira
$voice->Voice = $voice->GetVoices()->Item(1);
 
// Change $voice_file_stream to David
$voice_file_stream->Voice = $voice_file_stream->GetVoices()->Item(0);
 
// Have voices announce themselves
//$voice->Speak($voice->Voice->GetDescription); // (Zira)
//$voice_file_stream->Speak($voice_file_stream->Voice->GetDescription); // (David)
 
 
/*
Select Stream Quality:
 
11kHz 8Bit Mono = 8
11kHz 8Bit Stereo = 9
11kHz 16Bit Mono = 10
11kHz 16Bit Stereo = 11
...
16kHz 8Bit Mono = 16
16kHz 8Bit Stereo = 17
16kHz 16Bit Mono = 18;
16kHz 16Bit Stereo = 19
...
32kHz 8Bit Mono = 28
32kHz 8Bit Stereo = 29
32kHz 16Bit Mono = 30
32kHz 16Bit Stereo = 31
...
*/
// Set stream quality
$file_stream->Format->Type = 17; // 16kHz 8Bit Stereo
 
/*
Select Speech StreamFile Mode:
Read = 0
ReadWrite = 1
Create = 2
CreateForWrite = 3
*/
$mode = 3;
 
 
// Have $voice (Zira) announce beginning file stream
$voice->Speak('Opening audio file stream');
 
// Output TTS to File
$file_stream->Open($filename, $mode); // Open stream and create file
$voice_file_stream->AudioOutputStream = $file_stream; // Begin streaming TTS
// Have $voice_file_stream (David) speak $statement
$voice_file_stream->Speak($statement);
$file_stream->Close; // Close stream
 
// Have $voice (Zira) announce file stream completion
$voice->Speak('File stream complete');
</syntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(call 'espeak "This is an example of speech synthesis.")</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
Capture system disk label information as an array of strings:
<lang PowerShell>
Add-Type -AssemblyName System.Speech
 
Line 228 ⟶ 643:
$anna.Speak("I'm sorry Dave, I'm afraid I can't do that.")
$anna.Dispose()
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
<syntaxhighlight lang="python">
import pyttsx
 
engine = pyttsx.init()
engine.say("It was all a dream.")
engine.runAndWait()
</syntaxhighlight>
 
=={{header|Quackery}}==
 
Mac specific.
 
<syntaxhighlight lang="Quackery"> [ $ /
import subprocess
subprocess.run(["say",
string_from_stack()])
/ python ] is speak ( $ --> )
 
$ "This is an example of speech synthesis" speak</syntaxhighlight>
 
=={{header|Racket}}==
Should work on all platforms.
<langsyntaxhighlight lang="racket">
#lang racket
(require racket/lazy-require)
Line 245 ⟶ 681:
[else (error 'speak "I'm speechless!")]))
(speak "This is an example of speech synthesis.")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>run 'espeak', 'This is an example of speech synthesis.';</syntaxhighlight>
 
=={{header|REXX}}==
{{works with|Windowx/XP or later}}
Programming note: &nbsp; This REXX program uses a freeware program &nbsp; NIRCMD &nbsp; to interface with the Microsoft Windows speech synthesizer program &nbsp; '''SAM''', &nbsp; a text to speech using a male voice. &nbsp; SAM can possibly be configured to use other voices with later releases of Windows. &nbsp; More recent Microsoft Windows have another speech synthesizer program: &nbsp; ANNA.
<langsyntaxhighlight lang="rexx">/*REXX program uses a C.L. command line interface to invoke Windows SAM for speech synthesis.*/
parse arg t; t=space(t) /*get the (optional) text from the C.L.*/
if t=='' then signalexit done /*Nothing to say? Then exit program.*/
dquote= '"'
 
rate= 1 /*talk: -10 (slow) to 10 (fast). */
homedrive=value('HOMEDRIVE',,'SYSTEM') /*get HOMEDRIVE location of \TEMP */
tmp =value('TEMP',,'SYSTEM') /* " TEMP directory name. /* [↓] where the rubber meets the road*/
'NIRCMD' "speak text" dquote t dquote rate /*NIRCMD invokes Microsoft's Sam voice*/
if homedrive=='' then homedrive='C:' /*use the default if none was found. */
if tmp=='' then tmp=homedrive'\TEMP' /* " " " " " " " /*stick a fork in it, we're all done. */</syntaxhighlight>
/*code could be added here to get a ···*/
/* ··· unique name for the TEMP file.*/
tFN='SPEAK_IT'; tFT='$$$' /*use this name for the TEMP's fileID.*/
tFID=homedrive||'\TEMP\' || tFN"."tFT /*create temporary name for the output.*/
call lineout tFID,t /*write text ──► temporary output file.*/
call lineout tFID /*close the output file just to be neat*/
'NIRCMD' "speak file" tFID /*NIRCMD invokes Microsoft's Sam voice*/
'ERASE' tFID /*clean up (delete) the TEMP file.*/
 
done: /*stick a fork in it, we're all done. */</lang>
Note: &nbsp; The name of the above REXX program is &nbsp; '''speak.rex'''<br>
'''usage''' &nbsp; using the command:
<pre>
speak This is an example of speech synthesis.
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
 
load "guilib.ring"
 
myApp = New qApp
{
Text = "Hello. This is an example of speech synthesis"
voice = new QTextToSpeech(null)
voice.Say(Text)
exec()
}
 
</syntaxhighlight>
 
{{out}}
<pre>
 
"Hello. This is an example of speech synthesis"
 
</pre>
 
 
 
 
 
 
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
load "guilib.ring"
load "stdlib.ring"
 
MyApp = New qApp {
 
win1 = new qWidget() {
 
setwindowtitle("Hello World")
setGeometry(100,100,370,250)
 
Text = "This is an example of speech synthesis"
Text = split(Text," ")
 
label1 = new qLabel(win1) {
settext("What is your name ?")
setGeometry(10,20,350,30)
setalignment(Qt_AlignHCenter)
}
 
btn1 = new qpushbutton(win1) {
setGeometry(10,200,100,30)
settext("Say Hello")
setclickevent("pHello()")
}
 
btn2 = new qpushbutton(win1) {
setGeometry(150,200,100,30)
settext("Close")
setclickevent("pClose()")
}
 
lineedit1 = new qlineedit(win1) {
setGeometry(10,100,350,30)
}
 
voice = new QTextToSpeech(win1) {
}
show()
}
exec()
}
 
Func pHello
lineedit1.settext( "Hello " + lineedit1.text())
for n = 1 to len(Text)
voice.Say(Text[n])
see Text[n] + nl
next
 
Func pClose
MyApp.quit()
</syntaxhighlight>
{{out}}
<pre>
This
is
an
example
of
speech
synthesis
</pre>
 
=={{header|Ruby}}==
Using this module to encapsulate operating system lookup
<langsyntaxhighlight lang="ruby">module OperatingSystem
require 'rbconfig'
module_function
Line 296 ⟶ 820:
def windows?; operating_system == :windows; end
def mac?; operating_system == :mac; end
end</langsyntaxhighlight>
 
{{libheader|win32-utils}}
{{works with|Ruby|1.9}}
Uses <code>espeak</code> on Linux, <code>say</code> on Mac, and the win32 SAPI library on Windows.
<langsyntaxhighlight lang="ruby">load 'operating_system.rb'
 
def speak(text)
Line 317 ⟶ 841:
end
 
speak 'This is an example of speech synthesis.'</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|FreeTTS|1.2}}
<langsyntaxhighlight lang="scala">import javax.speech.Central
import javax.speech.synthesis.{Synthesizer, SynthesizerModeDesc}
 
Line 370 ⟶ 894:
|with its lapping disasters
|is feared and hearkened.""".stripMargin)
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func text2speech(text, lang='en') {
Sys.run("espeak -v #{lang} -w /dev/stdout #{text.escape} | aplay");
}
text2speech("This is an example of speech synthesis.");</langsyntaxhighlight>
 
=={{header|Swift}}==
OS X comes with a program called "say," that does speech.
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
let task = NSTask()
task.launchPath = "/usr/bin/say"
task.arguments = ["This is an example of speech synthesis."]
task.launch()</langsyntaxhighlight>
 
=={{header|Tcl}}==
This just passes the string into the Festival system:
<langsyntaxhighlight lang="tcl">exec festival --tts << "This is an example of speech synthesis."</langsyntaxhighlight>
Alternatively, on MacOS X, you'd use the system <code>say</code> program:
<langsyntaxhighlight lang="tcl">exec say << "This is an example of speech synthesis."</langsyntaxhighlight>
On Windows, there is a service available by COM for speech synthesis:
{{libheader|tcom}}
<langsyntaxhighlight lang="tcl">package require tcom
 
set msg "This is an example of speech synthesis."
set voice [::tcom::ref createobject Sapi.SpVoice]
$voice Speak $msg 0</langsyntaxhighlight>
Putting these together into a helper procedure, we get:
<langsyntaxhighlight lang="tcl">proc speak {msg} {
global tcl_platform
if {$tcl_platform(platform) eq "windows"} {
Line 412 ⟶ 936:
}
}
speak "This is an example of speech synthesis."</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 418 ⟶ 942:
 
{{works with|Bourne Shell}} {{works with|bash}}
<langsyntaxhighlight lang="bash">#!/bin/sh
espeak "This is an example of speech synthesis."</langsyntaxhighlight>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vbs">
Dim message, sapi
message = "This is an example of speech synthesis."
Set sapi = CreateObject("sapi.spvoice")
sapi.Speak message
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
The ability to call external processes such as ''espeak'' is expected to be added to Wren-cli in the next release. In the meantime, we embed the following Wren script in a minimal C host (no error checking) to complete this task.
<syntaxhighlight lang="wren">/* Speech_synthesis.wren */
 
class C {
foreign static getInput(maxSize)
 
foreign static espeak(s)
}
 
System.write("Enter something to say (up to 100 characters) : ")
var s = C.getInput(100)
C.espeak(s)</syntaxhighlight>
<br>
We now embed this in the following C program, compile and run it.
<syntaxhighlight lang="c">/* gcc Speech_synthesis.c -o Speech_synthesis -lwren -lm */
 
#include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include "wren.h"
 
void C_getInput(WrenVM* vm) {
int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;
char input[maxSize];
fgets(input, maxSize, stdin);
__fpurge(stdin);
input[strcspn(input, "\n")] = 0;
wrenSetSlotString(vm, 0, (const char*)input);
}
 
void C_espeak(WrenVM* vm) {
const char *arg = wrenGetSlotString(vm, 1);
char command[strlen(arg) + 10];
strcpy(command, "espeak \"");
strcat(command, arg);
strcat(command, "\"");
system(command);
}
 
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput;
if (isStatic && strcmp(signature, "espeak(_)") == 0) return C_espeak;
}
}
return NULL;
}
 
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
 
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
 
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "Speech_synthesis.wren";
char *script = readFile(fileName);
wrenInterpret(vm, module, script);
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>
 
=={{header|Zoomscript}}==
For typing:
<syntaxhighlight lang="zoomscript">speak "This is an example of speech synthesis."</syntaxhighlight>
For importing:
 
¶0¶speak "This is an example of speech synthesis."
 
=={{header|ZX Spectrum Basic}}==
Line 433 ⟶ 1,051:
This example makes use of the Currah Speech Synthesizer peripheral device.
 
<langsyntaxhighlight lang="zx basic">10 LET s$="(th)is is an exampul of sp(ee)(ch) sin(th)esis":PAUSE 1</langsyntaxhighlight>
{{omit from|TI-83 BASIC}}
{{omit from|Maxima}}
9,476

edits