Book Image

Twilio Cookbook

By : Roger Stringer
Book Image

Twilio Cookbook

By: Roger Stringer

Overview of this book

Have you ever wanted to integrate phone features into a project you were working on? Maybe you wanted to send SMS messages to your customers about the latest sales? Maybe you want to set up a company directory with voice mail? Or maybe you want to add two factor authentication to your web sites to verify your users? Since Twilio was launched in 2007, developers have had a way to do these tasks. The power of Twilio's API is huge and lets you add any type of phone solution to your web site from 2-factor authentication for verifying your users, to setting up a company directory and a voice mail system. The possibilities are endless. "Twilio Cookbook" is your Swiss army knife for Twilio development, providing you with a number of clear step-by-step exercises. It helps you take advantage of the real power of the Twilio API, and gives you a good grounding in using it in your websites. This book looks at the Twilio API, and breaks down the mystery and confusion that surrounds adding telephone functionality to your websites. As you go through the recipes, you will learn how to take advantage of the Twilio API quickly and painlessly. You will learn how to build your own IVR system, company directory, and voicemail box, and also how to set up a 2-factor authentication system to verify users, track orders via SMS, send surveys using SMS, allow users to buy phone numbers, set up and delete sub-accounts, and check to see if a human is answering a phone call. We will also combine Twilio with other APIs to build a handy local search system such as a local business search, movie listings search, and web search. If you want to take advantage of using Twilio's API to add telephone functionality to your websites, then this book is for you. "Twilio Cookbook' will leave you with a black belt in Twilio development and enable you to integrate the API into your websites.
Table of Contents (17 chapters)
Twilio Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Setting up Text-to-Speech


The final recipe of this chapter is going to use the Twilio Client to add handy functionality on your site.

Text-to-Speech is useful for having a voice read back text on a web page. You could do this by having a textbox of text that gets read back; or maybe you want to select text on a web page to be read back to a visitor.

Twilio Client is also handy for doing phone work straight from your browser.

Getting ready

The complete source code for this recipe can be found at Chapter1/Recipe7.

How to do it...

We're going to use the Twilio Client to set up a form where people can type in a message and have it spoken back to them either by a male or female voice.

  1. First, since this is using the Twilio Client, you need to set up a Twiml app under your account.

    Click on the Create TwiML App button and enter a name for your app. Also, you'll need to enter a URL for the Voice. In this case, set it to the URL where you have uploaded incoming_call.php, that is, http://MYWEBSITE.COM/incoming_call.php.

    Now, go back to the application list and you will see your new app. Look at the line directly beneath the name of your app; this is your app SID. Copy that as you will need it for this recipe.

  2. Download the Twilio Helper Library from https://github.com/twilio/twilio-php/zipball/master and unzip it.

  3. Upload the Services/ folder to your website.

  4. Upload config.php to your website and make sure the following variables are set:

    <?php
      $accountsid = '';  //  YOUR TWILIO ACCOUNT SID
      $authtoken = '';  //	  YOUR TWILIO AUTH TOKEN
      $fromNumber = '';  //  PHONE NUMBER CALLS WILL COME FROM
    ?>
  5. Let's create a file on your website called text-to-speech.php:

    <?php
      require_once('Services/Twilio/Capability.php');
      include("config.php");
      $APP_SID = 'YOUR APP SID';
      $token = new Services_Twilio_Capability($accountsid,$authtoken);
      $token->allowClientOutgoing($APP_SID);
    ?>
    <html> 
    <head> 
      <title>Text-To-Speech</title>
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
      <script type="text/javascript"src="//static.twilio.com/libs/twiliojs/1.1/twilio.min.js"></script>
      <script type="text/javascript"> 
        Twilio.Device.setup("<?php echo $token->generateToken();?>",{"debug":true});
        $(document).ready(function() {
          $("#submit").click(function() {
            speak();
          });
        });
        function speak() {
          var dialogue = $("#dialogue").val();
          var voice =$('input:radio[name=voice]:checked').val();
          $('#submit').attr('disabled', 'disabled');
          Twilio.Device.connect({ 'dialogue' :dialogue, 'voice' : voice });
        }
        Twilio.Device.disconnect(function (conn) {
          $('#submit').removeAttr('disabled');
        });
      </script> 
    </head> 
    <body> 
    <p> 
      <label for="dialogue">Text to be spoken</label> 
      <input type="text" id="dialogue" name="dialogue"size="50">
    </p>
    <p>
      <label for="voice-male">Male Voice</label>
      <input type="radio" id="voice-male" name="voice"value="1" checked="checked"> 
      <label for="voice-female">Female Voice</label> 
      <input type="radio" id="voice-female" name="voice"value="2">
    </p>
    <p>
      <input type="button" id="submit" name="submit"value="Speak to me"> 
    </p> 
    </body> 
    </html>

    Tip

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

  6. Now, let's create another file on your website called incoming_call.php, which is the file Twilio Client will call. This will then read back the text you entered using either a male or female voice:

    <?php
      header('Content-type: text/xml');
      echo '<?xml version="1.0" encoding="UTF-8" ?>';
      $dialogue = trim($_REQUEST['dialogue']);
      $voice = (int) $_REQUEST['voice'];
      if (strlen($dialogue) == 0){
      $dialogue = 'Please enter some text to be spoken.';
      }
    if ($voice == 1){
      $gender = 'man';
    }else {
      $gender = 'woman';
    }
    ?>
    <Response>
      <Say voice="<?php echo $gender; ?>"><?php echo htmlspecialchars($dialogue); ?></Say>
    </Response>

How it works...

In step 1, we set up our Twiml app in our Twilio account.

In steps 2 and 3, we downloaded and installed the Twilio Helper Library for PHP.

In step 4, we uploaded config.php that contains our authentication information to talk to Twilio's API.

Using Twilio Client, this recipe will read the content of a text box and play it back to you in either a male or female voice.

Twilio Client is a nice addition to the Twilio API that lets you do phone work straight from the browser. This way, you can add functionality directly to your web apps.