Tuesday, February 11, 2014

How to build a voice application using Twilio?

This topic talks about step by step process to build a voice application using Java and Twilio. In this blog, we will see how to make a call to another phone number using Twilio and also convert browser as a phone and start receiving calls on browser.

A little background…

Twilio is a cloud communications company which provides Web APIs to build voice, VOIP and SMS applications. In this post, we will cover how to use these APIs to make an outbound call and start conversation.

Twilio handles call instructions in realtime using TwiML(Twilio Markup XML) hosted as a Web API. 

Figure 1: Outbound call flow using Twilio

  1. An application submits a request to Twilio using their REST API with the parameters:
  2. From=+14159998888
  3. Twilio makes a call to the number specified in To field and waits for an answer.
  4. Once the call is answered, Twilio intiate step to fetch the call instructions.
  5. Twilio requests the URL specified in step#1 to retrieve TwiML providing instructions to be followed.
  6. TwiML which is in XML format is returned to Twilio. A sample TwiML is below:
  7. <?xml version="1.0" encoding="UTF-8" ?>
    <Say voice=”woman”>Hello World</Say> 
  8. Twilio parses the TwiML and identifies the next actions to take.
  9. If TwiML contains <Say> it converts the text to speech and plays to the call receiver.
  10. If TwiML contains <Dial> then makes another outbound call to the number specified.
  11. Twilio connects both the caller for the conversation.


  1. Sign up for a Twilio Account. Sign up is free. On sign up, a Twilio phone number is provided.
  2. A webserver where TwiML can be hosted. We will use Heroku for this purpose. Setup the Heroku environment, it will provide a dyno on which TwiML will be hosted.
Get Started
Step 1: Write a TwiML and deploy it on web
  1. Host a XML file on Heroku which will respond with TwiML. Please refer Heroku quickstart guide to deploy XML on Heroku. Heroku will provide a url which can be accessed through your browser.
  2. The XML file is below.
  3. <?xml version="1.0" encoding="UTF-8" ?>
    <Say voice=”woman”>Hi There !!! You successfully made the first call using Twilio</Say>
  4. Deploy this jsp under webapp onto heroku. You should be able to access this jsp page by accessing the url http://Your-Dyno-Name.herokuapp.com/dial.xml. This will show TwiML on your browser. Later, we will discuss how to pass this url to Twilio so that it can access and identify call instructions.
Step 2: Make an Outbound call
  1. Below Java function shows code to make a call using Twilio.
  2. private void makeCall(String phoneNumber) {
      // Twilio AccountSid and AuthToken. This is copied from Twilio account page 
      // Instantiate a new Twilio Rest Client 
      TwilioRestClient client = new TwilioRestClient(AccountSid, AuthToken);
      // callfactory to make outbound call.
      CallFactory callFactory = client.getAccount().getCallFactory(); 
      // Create a map of call parameters to be submitted to Twilio in REST API call
      Map<String, String> callParams = new HashMap<String, String>();
      callParams.put("To", phoneNumber); // phone number to call
      callParams.put("From", "+14159998888"); // Twilio number - provided by Twilio
      // TwiML url for the Twilio to connect, once call is answered
      callParams.put("Url", "http://Your-Dyno-Name.herokuapp.com/dial.xml"); 
      // Make the call
      try {
          Call call = callFactory.create(callParams);
          System.out.println("Call Sid = " + call.getSid());
          // Poll REST API to get the call status
          while (call.getStatus().equals("queued") || call.getStatus().equals("ringing") || call.getStatus().equals("in-progress")) {
              // keep polling the rest api to get the current status of the call
              call = account.getCall(call.getSid());
              System.out.println("current call status = " + call.getStatus());
              try {
                  Thread.sleep(2000); //Pull the status every 2 secs
              } catch (InterruptedException e) {
          } //end of while - call is completed
          // call is completed  
          System.out.println("Call Duration: " + call.getDuration() + " seconds");
      } catch (TwilioRestException e) {
    } //end method
  3. Run this Java application. It will make an outbound call to the number specified.
  4. On picking up the number, hear the message mentioned in TwiML, played by Twilio.
Step 3: Connect with another phone number
  1. Modify the TwiML to add <Number> tag. <Number> within <Dial> instructs Twilio to dial that number. On answer, connect it with the number for which this TwiML is requested.
  2. Modified TwiML looks as below:
  3. <?xml version="1.0" encoding="UTF-8" ?>
  4. Run the above Java code. Once the outbound call is picked up Twilio will make a request to TwiML which will instruct about the next steps. In this example, <Number> verb is instructing to make a connection with the number +1-123-456-7890.
  5. Now communication channel between phones 1-123-456-7890 and the phone number specified as parameter to makeCall() has been established and conversation has started.
Step 4: Connect with browser
  1. Modify the TwiML to add <Client> tag. <Client> within <Dial> instructs Twilio to dial that client which registered with Twilio using Twilio client script.
  2. Modified TwiML looks as below:
  3. <?xml version="1.0" encoding="UTF-8" ?>
  4. Write a client.jsp (refer example here) page which registers client with Twilio. The key specified as parameter in allowClientOutgoing('APxxxxxxxxxxxxxx') is Twilio's App Sid which you can get after registering a Twilio App. This is needed if you are going to make an outgoing call from browser. For incoming specifying clientname in allowClientIncoming("alice"); is good enough.
  5. The name specified in allowIncomingConnection() is the name which must be used for <Client> in TwiML.
  6. Deploy this JSP on Heroku.
  7. Access the JSP from browser and it will register client with Twilio.
  8. Run the java program which will make connection to this TwiML which in turn will instruct to make a connection with the <Client>
  9. On browser you will see a pop up asking to accept the incoming call.
  10. Click Ok and start having conversation with the person on phone using your browser.
Final round up...
The above example shows how a communication channel can be established between a phone and web-browser. This is just scratching the surface of TwiML. There is of course plenty of more functionality which is needed to be explored, enabling developers to build a very sophisticated voice application. 

Thanks for stopping by. Please drop your comments/suggestions below.

No comments:

Post a Comment