Sunday, March 1, 2009: Mac OS X's say command « from the old blog archive »

This isn't new at all, but I like it a lot. The say command is very handy when you want your Mac to say something. You can use the say command from the terminal, via SSH, or on a web application that can execute the say command on the Mac.

Lately, I made a small web app running on the Mac, with an intention to access it from localhost only. I made an app that basically searchs for tweets that matches a predefined query every once a while, show it on the screen with a very big font, and read it aloud. That way, if I am near my MacBook but I am working on my PC, I can just listen to the tweet. If I am far from the MacBook or can't hear it clearly, I can just look at the screen.

The following code will only work when you host the script on your Mac. If you access the script on other PC, it will still read aloud on your Mac.

Here is the PHP code I use in order for a Mac to say:

<?php exec ('say ' . escapeshellarg(stripslashes($_GET['q']))); ?>

And the JavaScript code.

function say(something, callback) {

     var x = new XMLHttpRequest();
     // all browsers on the mac already supports xmlhttprequest
     // except the ancient ones

     x.open ('get', 'say.php?q=' + encodeURIComponent(something), true);
     x.onreadystatechange = function() {
         if (x.readyState == 4) {
             if (callback) (callback) ();
         }
     };
     x.send ('');

}

Now you can go ahead and implement whatever the hell you want.