RingDotNetfor Ring

Text to speech

Windows has voices that read a text aloud. The System.Speech package from nuget.org gives them to a program. This lesson lists the voices, writes speech to a WAV file without any sound, compares speeds, and speaks aloud on request. It also shows what to do with a package that has a different DLL for each system.

What you will learn#

Note

This lesson runs on Windows only. The voices are part of Windows, and the program says so on another system. (Linux and macOS have their own speech programs, which a Ring program can start as a command, as in the lesson Working with other programs.)

A package with a DLL for each system#

The package System.Speech has the same name and the same classes on every system, but only on Windows does it do anything. A package like that contains an empty DLL for general use and the real one in a folder for Windows. A plain dotnet publish copies the empty one, and the first call stops with Speech is not supported on this platform. The project file therefore says which system the output is for:

samples/UsingDotNet/tutorials/Speech/Speech.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <AssemblyName>Speech</AssemblyName>
    <DebugType>none</DebugType>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>
    <SelfContained>false</SelfContained>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="System.Speech" Version="9.0.0" />
  </ItemGroup>
</Project>

RuntimeIdentifier win-x64 makes dotnet publish take the files for Windows, 64-bit, and SelfContained false keeps the output small, because the program uses the .NET that is already installed. Use the same setting for any package that is meant for one system.

The steps#

The steps are the ones of the lessons on packages (A NuGet package and the lessons after it): a project file, dotnet publish, wrapassembly.ring (only the namespace System.Speech.Synthesis), then dnLoad and dnImportFrom.

The program#

samples/UsingDotNet/tutorials/ch13_speech.ring
# text to speech - System.Speech (a package from nuget.org) makes a voice of Windows speak, or writes the speech to a WAV file
#   (the project is in the folder Speech: Speech.csproj names the package for Windows, and Empty.cs is the one source file a project needs)
#   Run it with --speak to hear the voice; without it the program writes the speech to a file, silently.
load "dotnet.ring"

using { "System.IO" }

if not iswindows()
	? "The voices are part of Windows, so this lesson runs on Windows only."
	bye
ok

cHere = currentdir()
cDll = cHere + "/Speech/libs/System.Speech.dll"
cClasses = cHere + "/Speech/classes"

# STEP 1. Get the package (nuget.org the first time) with dotnet publish. The project says RuntimeIdentifier win-x64: the package has an
# empty version of the DLL for every system, and the real one only for Windows, which a publish for Windows puts in the folder.
if not fexists(cDll)
	? "getting the package..."
	system("dotnet publish Speech -c Release -o Speech/libs -nologo -v q > nul")
ok
if not fexists(cDll)
	? "The package could not be restored. It is downloaded from nuget.org the first time, so the computer needs the internet once."
	bye
ok

# STEP 2. Make Ring classes for the namespace that makes speech
chdir("../../../tools/dotnettools")
system(exefilename() + " wrapassembly.ring " + cDll + " " + cClasses + " System.Speech.Synthesis > nul")
chdir(cHere)

# STEP 3. Load the assembly and the classes
dnLoad(cDll)
dnImportFrom(cClasses + "/","System.Speech.Synthesis")

func main

	oVoice = new SpeechSynthesizer()

	# 1. The voices that are installed (the names depend on the computer, so the program only counts them)
	aVoices = oVoice.GetInstalledVoices(NULL).toList()
	? "1. installed voices: " + len(aVoices) + ", at least one: " + (len(aVoices) > 0)

	# 2. Speech goes to a file: SetOutputToWaveFile, then Speak. Rate is from -10 (slow) to 10 (fast): a slower voice needs more time,
	#    so its file is bigger.
	cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet-speech.wav"])
	cText = "Hello from Ring. This sentence is spoken by a voice of Windows."
	nSizeNormal = speakToFile(oVoice,cText,0,cFile)
	nSizeSlow = speakToFile(oVoice,cText,-5,cFile)
	nSizeFast = speakToFile(oVoice,cText,5,cFile)
	? "2. a WAV file was written: " + (nSizeNormal > 10000)
	? "   the slow voice makes a bigger file than the normal one, and the normal one a bigger file than the fast one: " + (nSizeSlow > nSizeNormal and nSizeNormal > nSizeFast)
	new File().Delete(cFile)

	# 3. To hear it, the output goes back to the speakers: SetOutputToDefaultAudioDevice, and Speak waits until the text is spoken
	if find(sysargv,"--speak") > 0
		oVoice.SetOutputToDefaultAudioDevice()
		oVoice.Rate = 0
		? "3. speaking..."
		oVoice.Speak(cText)
	else
		? "3. (run the program with --speak to hear it)"
	ok
	oVoice.Dispose()

# speaks a text to a WAV file with a rate and gives the size of the file
func speakToFile oVoice, cText, nRate, cFile

	oVoice.Rate = nRate
	oVoice.SetOutputToWaveFile(cFile)
	oVoice.Speak(cText)
	oVoice.SetOutputToNull()          # closes the file
	return new FileInfo(cFile).Length
Output
1. installed voices: 2, at least one: 1
2. a WAV file was written: 1
   the slow voice makes a bigger file than the normal one, and the normal one a bigger file than the fast one: 1
3. (run the program with --speak to hear it)

Run it with --speak to hear the voice.

How it works#

The voices#

new SpeechSynthesizer() is the speaking voice. GetInstalledVoices(NULL) is a list of the voices of the computer, and toList() copies it into a Ring list. Each item describes one voice (its name, language and gender in VoiceInfo). The names are different on every computer, so the program only counts them. SelectVoice(name) picks one by name.

Speech to a file#

SetOutputToWaveFile(cFile) sends the speech to a WAV file and not to the speakers, and Speak(cText) makes it. That is quiet, so it can be used in a test: the program checks the size of the file. To end the file the output is set to nothing, with SetOutputToNull(), so that the file is closed before it is read.

Rate is a number from -10 (slow) to 10 (fast). A slow voice needs more time for the same text, so its WAV file is bigger: that is what the second line of the output tests. The WAV format is explained in the lesson Sound, and the file can be played with a SoundPlayer.

Speaking aloud#

SetOutputToDefaultAudioDevice() sends the speech to the speakers again, and Speak waits until the text is spoken. SpeakAsync starts the speech and returns at once, but then the program must stay alive until the voice has finished; the lessons on timers and on tasks show ways to wait. The events of the synthesizer (the end of a sentence, for example) are raised while the speech runs; callbacks into Ring work only during a call from Ring (the lesson Callbacks and events), so this lesson does not use them.

Before you use it#

What you learned#

Exercises#

  1. Run the program with --speak, and change the text.
  2. Select a second voice with SelectVoice (print the names first: aVoices[1].VoiceInfo.Name) and compare how the two sound.
  3. Write a function that reads the lines of a text file one by one with Speak.
  4. Write the speech to a WAV file and play it with the program of the lesson Sound.

Next#

Sound

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.