Google Text to Speech with AutoIt

Thought I'd share my simple example of using Google's Text to Speech API with AutoIt.

The stupid-simple app will let you preview the text-to-speech conversion and save an mp3.


#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#include <inet.au3>
#include <sound.au3>
#NoTrayIcon

$gui = GUICreate("Text to Speech Maker", 599, 300, -1, -1)
$Label1 = GUICtrlCreateLabel("Message:", 8, 24, 50, 17)
$Edit1 = GUICtrlCreateEdit("", 64, 24, 521, 201)
GUICtrlSetData(-1, "Hello, how are you doing?")
$Button1 = GUICtrlCreateButton("Preview", 400, 248, 91, 25)
$Button2 = GUICtrlCreateButton("Save as MP3", 496, 248, 91, 25)
$Label2 = GUICtrlCreateLabel("Created By Brad (c) 2010 - PingTurtle.com", 408, 280, 178, 17)
GUISetState(@SW_SHOW)

While 1
	$nMsg = GUIGetMsg()
	Switch $nMsg
		Case $GUI_EVENT_CLOSE
			Exit
		Case $button1
			GUICtrlSetState( $Button1, $GUI_DISABLE )
			preview()
			GUICtrlSetState( $Button1, $GUI_ENABLE )
		Case $button2
			savemp3()
	EndSwitch
WEnd

Func preview()
	$file = getMP3( " " & GUICtrlRead( $Edit1 ) )
	If $file = -1 Then
		MsgBox(16, "Error", "Could not get data from the internet, Make sure you are connected." )
		Return
	EndIf
	$sound = _SoundOpen( $file )
	_SoundPlay($sound, 1)
	_SoundClose($sound)
EndFunc

Func savemp3()
	$file = getMP3( " " & GUICtrlRead( $Edit1 ) )
	If $file = -1 Then
		MsgBox(16, "Error", "Could not get data from the internet, Make sure you are connected." )
		Return
	EndIf
	$save = FileSaveDialog( "Save MP3", @MyDocumentsDir, "MP3 Files (*.mp3)", 18, "speech.mp3", $gui )
	If @error Then Return False
	If Not StringRight( $save, 4 ) = ".mp3" Then $save &= ".mp3"
	FileMove( $file, $save, 9 )
	MsgBox(0, "Info", "Your MP3 file has been saved." )
EndFunc

Func getMP3( $text )
	SplashTextOn( "Please wait...", "Please wait..."&@crlf&"Rendering to speech...", 400, 150, -1, -1, 33 )
	$baseurl = "http://translate.google.com/translate_tts?tl=en&q=" & _INetExplorerCapable( $text )
	$filename = "txt2spch.mp3"
	FileDelete( @TempDir & "\" & $filename)
	InetGet( $baseurl, @TempDir & "\" & $filename, 1 )
	If @error Then Return -1
	SplashOff()
	Return @TempDir & "\" & $filename
EndFunc

I probably have some unnecessary includes in there... but whatever.



Posted 1/24/2012 by Brad