Using a speech engine to highlight words: Difference between revisions

m
m (Reword the task (based on comments in discussion page) to make it clearer what was intended)
m (→‎{{header|Wren}}: Minor tidy)
 
(30 intermediate revisions by 17 users not shown)
Line 1:
{{draft task}}[[Category:Speech synthesis]][[Category:Temporal media]]
Display a piece of text and produce spoken output via a speech engine.
Send a piece of text in a simple GUI through a text-to-speech engine (producing spoken output). At the same time as each word is being spoken, highlight the word in the GUI. (The GUI does not need to be interactive, but some extra kudos for allowing users of the code to provide their own text.)
 
As each word is being spoken, highlight the word on the display.
 
In languages where cursor control and highlighting are not possible, it is permissible to output each word as it is spoken.
 
 
;Related task:
:*   [[Speech_synthesis|speech synthesis]]
<br><br>
 
=={{header|AutoHotkey}}==
We use the simple SAPI.SPVoice COM Object and a parsing loop.
The highlighting is done with [http://msdn.microsoft.com/en-us/library/bb761661 EM_SETSEL] and Notepad. Rather crude, but it works. Due to the simplistic nature of the parsing loop, the text ends with a space.
<langsyntaxhighlight AutoHotkeylang="autohotkey">SetTitleMatchMode 2
EM_SETSEL := 0x00B1
 
Line 23 ⟶ 32:
}
Else word .= lf, i++
}</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)
Shell "mshta vbscript:Execute(""CreateObject(""""SAPI.SpVoice"""").Speak("""""+Texto+""""")(window.close)"")"
End Sub
 
Function Split(Texto As String, SplitL As String, Direcc As Byte = 0) As String
Dim As Integer LocA = Instr(Texto, SplitL)
Return Iif(Direcc <= 0, Left(Texto, LocA), Right(Texto, Len(Texto) - LocA))
End Function
 
Dim As String texto = "Actions speak louder than words"
Dim As String palabra()
Dim As Integer cont = -1
Do
cont += 1
Redim Preserve palabra(cont)
palabra(cont) = Split(texto," ")
texto = Right(texto, Len(texto)-Len(palabra(cont)))
If Len(palabra(cont)) = 0 Then palabra(cont) = texto : Exit Do
Loop
 
For n As Integer = 0 To Ubound(palabra)
Print palabra(n)
Speak palabra(n)
Next n</syntaxhighlight>
 
 
=={{header|Go}}==
{{works with|Ubuntu 16.04}}
<br>
This uses the eSpeak speech synthesizer which is invoked for each word in the text. As the word is spoken it is printed to the terminal in capitalized form (and the previous word is uncapitalized). After a second's delay the final word is uncapitalized.
 
Very robotic but it works.
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"log"
"os/exec"
"strings"
"time"
)
 
func main() {
s := "Actions speak louder than words."
prev := ""
prevLen := 0
bs := ""
for _, word := range strings.Fields(s) {
cmd := exec.Command("espeak", word)
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
if prevLen > 0 {
bs = strings.Repeat("\b", prevLen)
}
fmt.Printf("%s%s%s ", bs, prev, strings.ToUpper(word))
prev = word + " "
prevLen = len(word) + 1
}
bs = strings.Repeat("\b", prevLen)
time.Sleep(time.Second)
fmt.Printf("%s%s\n", bs, prev)
}</syntaxhighlight>
 
 
=={{header|Julia}}==
{{trans|Go}}
<syntaxhighlight lang="julia">function speak(sentence, cmd = "/utl/espeak.bat")
for word in split(sentence)
s = replace(lowercase(word), r"[^a-z]" => "")
if length(s) > 0
print(uppercase(s))
run(`$cmd $s`)
sleep(1)
print("\b"^length(s))
end
print(word, " ")
end
end
 
speak("Are those 144 shy Eurasian footwear, cowboy chaps, or jolly earthmoving headgear?")
</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module UsingEvents {
Form 60, 32
Cls 5, 0
Pen 14
Declare WithEvents sp "SAPI.SpVoice"
That$="Rosetta Code is a programming chrestomathy site"
margin=(width-Len(That$))/2
EndStream=False
\\ this function called as sub routine - same scope as Module
\\ we can call it from event function too
Function Localtxt {
\\ move the cursor to middle line
Cursor 0, height/2
\\ using OVER the line erased with background color and then print text over
\\ ordinary Print using transparent printing of text
\\ $(0) set mode to non proportional text, @() move the cursor to sepecific position
Print Over $(0),@(margin), That$
}
Call Local LocalTxt()
Function sp_Word {
Read New StreamNumber, StreamPosition, CharacterPosition, Length
Call Local LocalTxt()
Cursor 0, height/2
Pen 15 {Print Part $(0), @(CharacterPosition+margin); Mid$(That$, CharacterPosition+1, Length)}
Refresh
}
Function sp_EndStream {
Refresh
EndStream=True
}
Const SVEEndInputStream = 4
Const SVEWordBoundary = 32
Const SVSFlagsAsync = 1&
With sp, "EventInterests", SVEWordBoundary+SVEEndInputStream
Method sp, "Speak", That$, SVSFlagsAsync
While Not EndStream {Wait 10}
Call Local LocalTxt()
}
UsingEvents
 
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="text">DynamicModule[{text = "This is some text.", words, i = 0},
Panel@Column@{Dynamic[
Row[Riffle[
If[i != 0, MapAt[Style[#, Red] &, #, i], #] &@(words =
StringSplit@text), " "]]], InputField[Dynamic@text, String],
Button["Speak",
While[i < Length@words, i++; FinishDynamic[]; Speak[words[[i]]];
Pause[Max[0.7, 0.12 StringLength[words[[i]]]]]]; i = 0]}]</syntaxhighlight>
 
=={{header|Nim}}==
{{trans|Go}}
Works on Linux but may also work on other platforms provided "espeak" is installed.
<syntaxhighlight lang="nim">import os, osproc, strutils
 
const S = "Actions speak louder than words."
 
var prev, bs = ""
var prevlen = 0
 
for word in S.splitWhitespace():
discard execProcess("espeak " & word)
if prevlen > 0:
bs = repeat('\b', prevlen)
stdout.write bs, prev, word.toUpper, ' '
stdout.flushFile()
prev = word & ' '
prevlen = word.len + 1
 
bs = repeat('\b', prevlen)
sleep(1000)
echo bs, prev</syntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/Speech.htm here].
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Speech.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;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">left</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">red</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">right</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">btn</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hbc</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dlg</span>
<span style="color: #000080;font-style:italic;">-- not sure why, but a leading space really helps...</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">` Highlight words as they are spoken.`</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">speech_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">pos</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">len</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">pos</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">pos</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">left</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: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">])</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">red</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: #000000;">pos</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">+</span><span style="color: #000000;">len</span><span style="color: #0000FF;">])</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">right</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: #000000;">pos</span><span style="color: #0000FF;">+</span><span style="color: #000000;">len</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..$])</span>
<span style="color: #7060A8;">IupSetAttributes</span><span style="color: #0000FF;">({</span><span style="color: #000000;">left</span><span style="color: #0000FF;">,</span><span style="color: #000000;">red</span><span style="color: #0000FF;">,</span><span style="color: #000000;">right</span><span style="color: #0000FF;">},</span> <span style="color: #008000;">"RASTERSIZE=x0"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupRefresh</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupRedraw</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</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: #004080;">atom</span> <span style="color: #000000;">rate</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">WINDOWS</span><span style="color: #0000FF;">?-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">:</span> <span style="color: #000080;font-style:italic;">-- -10..+10, voice dependent</span>
<span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span><span style="color: #0000FF;">?</span><span style="color: #000000;">0.3</span><span style="color: #0000FF;">:</span> <span style="color: #000080;font-style:italic;">-- 0.1..10, 0.5 = half speed</span>
<span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- linux, anyone?...</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: #000000;">rate</span><span style="color: #0000FF;">,</span><span style="color: #000000;">speech_cb</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: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">left</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">red</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`FGCOLOR="255 0 0"`</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">right</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">t3</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupFill</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">left</span><span style="color: #0000FF;">,</span><span style="color: #000000;">red</span><span style="color: #0000FF;">,</span><span style="color: #000000;">right</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">IupFill</span><span style="color: #0000FF;">()},</span>
<span style="color: #008000;">`FONT="Verdana, 18", MARGIN=0x20`</span><span style="color: #0000FF;">)</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;">hbc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupFill</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">btn</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">IupFill</span><span style="color: #0000FF;">()},</span><span style="color: #008000;">"MARGIN=0x10"</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;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hbc</span><span style="color: #0000FF;">}),</span><span style="color: #008000;">"TITLE=Speak"</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>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|Raku}}==
{{trans|Go}}
<syntaxhighlight lang="raku" line># 20200826 Raku programming solution
 
my \s = "Actions speak louder than words.";
my \prev = $ = "";
my \prevLen = $ = 0;
my \bs = $ = "";
 
for s.split(' ', :skip-empty) {
run "/usr/bin/espeak", $_ or die;
bs = "\b" x prevLen if prevLen > 0;
printf "%s%s%s ", bs, prev, $_.uc;
prev = "$_ ";
prevLen = $_.chars + 1
}
 
printf "%s%s\n", "\b" x prevLen, prev;</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.
 
Each word of the text is highlighted (by showing the word in uppercase). &nbsp; the terminal screen is cleared before showing the text that is being spoken; &nbsp; the repeated calls to the (Windows) speech engine makes for a slower speech rate.
<syntaxhighlight lang="rexx">/*REXX program uses a command line interface to invoke Windows SAM for speech synthesis.*/
parse arg t /*get the (optional) text from the C.L.*/
#= words(t)
if #==0 then exit /*Nothing to say? Then exit program.*/
dq= '"' /*needed to enclose text in dbl quotes.*/
rate= 1 /*talk: -10 (slow) to 10 (fast). */
/* [↓] where the rubber meets the road*/
do j=1 for #
x= word(t, j); upper x /*extract 1 word, capitalize it for HL.*/
if j==1 then LHS= /*obtain text before the spoken word. */
else LHS= subword(t, 1, j-1)
if j==# then RHS= /*obtain text after the spoken word. */
else RHS= subword(t, j+1)
'CLS' /*use this command to clear the screen.*/
say 'speaking: ' space(LHS x RHS) /*show text, one word is capitalized. */
oneWord= dq x dq /*surround a word in double quotes (").*/
'NIRCMD' "speak text" oneWord rate /*NIRCMD invokes Microsoft's Sam voice*/
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
Note: &nbsp; The name of the above REXX program is &nbsp; '''SPEAKHI.REX'''<br>
 
'''usage''' &nbsp; using the command:
<pre>
speakhi This is an example of speech synthesis.
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
load "guilib.ring"
 
MyApp = New qApp {
 
win1 = new qWidget() {
 
setwindowtitle("Hello World")
setGeometry(100,100,370,250)
 
Text = "Welcome to the Ring Programming Language"
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>
Welcome
to
the
Ring
Programming
Language
</pre>
 
=={{header|Ruby}}==
{{libheader|Shoes}}
I'm having difficulty figuring out how to get Shoes to update the GUI (like Tk's <code>update</code> command), so the user must click the button once for each word.
 
Uses the Ruby code from [[Speech synthesis]]
<syntaxhighlight lang="ruby">load 'speechsynthesis.rb'
 
if ARGV.length == 1
$text = "This is default text for the highlight and speak program"
else
$text = ARGV[1..-1].join(" ")
end
$words = $text.split
 
Shoes.app do
@idx = 0
 
stack do
@sentence = para(strong($words[0] + " "), $words[1..-1].map {|word| span(word + " ")})
button "Say word" do
say_and_highlight
end
end
 
keypress do |key|
case key
when :control_q, "\x11" then exit
end
end
 
def say_and_highlight
speak $words[@idx]
@idx = (@idx + 1) % $words.length
@sentence.replace($words.each_with_index.map {|word, idx| idx == @idx ? strong(word + " ") : span(word + " ")})
end
end</syntaxhighlight>
 
=={{header|Tcl}}==
This code uses the external <code>/usr/bin/say</code> program (known available on Mac OS X) as its interface to the speech engine; this produces rather stilted speech because it forces the text to be spoken one word at a time instead of as a whole sentence (in order to keep the highlighting synchronized).
{{libheader|Tk}}
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require Tk 8.5
proc say {text button} {
grab $button
$button configure -state disabled -cursor watch
update
set starts [$text search -all -regexp -count lengths {\S+} 1.0]
foreach start $starts length $lengths {
lappend strings [$text get $start "$start + $length char"]
lappend ends [$text index "$start + $length char"]
}
$text tag remove sel 1.0 end
foreach from $starts str $strings to $ends {
$text tag add sel $from $to
update idletasks
exec /usr/bin/say << $str
$text tag remove sel 1.0 end
}
grab release $button
$button configure -state normal -cursor {}
}
 
pack [text .t]
pack [button .b -text "Speak, computer!" -command {say .t .b}] -fill x
.t insert 1.0 "This is an example of speech synthesis with Tcl/Tk."</syntaxhighlight>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-str}}
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">/* Using_a_speech_engine_to_highlight_words.wren */
 
import "./str" for Str
 
class C {
foreign static usleep(usec)
 
foreign static espeak(s)
 
foreign static flushStdout()
}
 
var s = "Actions speak louder than words."
var prev = ""
var prevLen = 0
var bs = ""
for (word in s.split(" ")) {
if (prevLen > 0) bs = "\b" * prevLen
System.write("%(bs)%(prev)%(Str.upper(word)) ")
C.flushStdout()
C.espeak(word)
prev= word + " "
prevLen = word.count + 1
}
bs = "\b" * prevLen
C.usleep(1000)
System.print("%(bs)%(prev)")</syntaxhighlight>
<br>
We now embed this in the following C program, compile and run it.
<syntaxhighlight lang="c">/* gcc Using_a_speech_engine_to_highlight_words.c -o Using_a_speech_engine_to_highlight_words -lwren -lm */
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "wren.h"
 
void C_usleep(WrenVM* vm) {
useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);
usleep(usec);
}
 
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);
}
 
void C_flushStdout(WrenVM* vm) {
fflush(stdout);
}
 
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, "usleep(_)") == 0) return C_usleep;
if (isStatic && strcmp(signature, "espeak(_)") == 0) return C_espeak;
if (isStatic && strcmp(signature, "flushStdout()") == 0) return C_flushStdout;
}
}
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;
}
 
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
 
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
 
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "Using_a_speech_engine_to_highlight_words.wren";
char *script = readFile(fileName);
wrenInterpret(vm, module, script);
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>
 
{{omit from|EasyLang}}
9,476

edits