Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Twilio Cookbook

You're reading from   Twilio Cookbook The Twilio cookbook will enable all kinds of telephone usage, including SMS, on your websites. It's a totally practical guide with a hands-on approach to help you dig deep into the enormous potential of telephone facilities on the Web.

Arrow left icon
Product type Paperback
Published in Sep 2013
Publisher Packt
ISBN-13 9781782166061
Length 266 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Roger Stringer Roger Stringer
Author Profile Icon Roger Stringer
Roger Stringer
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Twilio Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
1. Into the Frying Pan 2. Now We're Cooking FREE CHAPTER 3. Conducting Surveys via SMS 4. Building a Conference Calling System 5. Combining Twilio with Other APIs 6. Sending and Receiving SMS Messages 7. Building a Reminder System 8. Building an IVR System 9. Building Your Own PBX 10. Digging into OpenVBX 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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime