Text to Speech, Yosemite, and JavaScript

I’d been waiting for the formal release of Yosemite so that I could play with JavaScript “automation”.  While tinkering I noticed a simple enough interface to the text-to-speech functions of OS/X.

As an early sample program, I wrote a little JavaScript program that will say (instead of sing) the lyrics to the song The Twelve Days of Christmas.

Other than the song lyrics, this code is open under the MIT/X11 license ( see http://www.mailsend-online.com/license2014.php )

To enter the program, invoke the Script Editor.  If the language listed in the upper-left corner shows “AppleScript”, change it to “JavaScript”.  Copy/paste this program in the editor.

Since the blog editor doesn’t always paste code cleanly without escaping certain symbols, you might want to copy and paste the code from here:

http://www.mailsend-online.com/src/0001.txt

App = Application.currentApplication();

App.includeStandardAdditions = true;

var days=[
   ["first", "a partridge in a pear tree." ],
   ["second","two turle doves,"],
   ["third","three French hens,"],
   ["fourth","four calling birds,"],
   ["fifth","five golden rings,"],
   ["sixth","six geese a laying"],
   ["seventh","seven swans a swimming,"],
   ["eighth","eight maids a milking,"],
   ["ninth","nine ladies dancing"],
   ["tenth","ten lords a leaping,"],
   ["elevnth","eleven pipers piping,"],
   ["twelfth","twelve drummers drummng,"]
];
   
function verse(whichDay) {
   whichDay--;   	 
   var pair=days[whichDay];
   App.say("On the "  + pair[0] + 
      " day of Christmas, my true love gave to me:");
   if(whichDay==0) {
      App.say(pair[1]);
	  return;
   }

   while(whichDay>0) { 
     App.say(pair[1]);
	 whichDay--;
	 pair=days[whichDay];
   }
   App.say("and "+days[0][1]);
}

for(i=1;i<12;i++) {
   verse(i);
}
Advertisements

About Jim Lawless

I've been programming computers for about 36 years ... 30 of that professionally. I've been a teacher, I've worked as a consultant, and have written articles here and there for publications like Dr. Dobbs Journal, The C/C++ Users Journal, Nuts and Volts, and others.
This entry was posted in Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s