Twilio

Voice Recorder


The Voice Recorder demo is an outgoing application that makes an outgoing call to a phone, lets the caller leave a recorded message, and provides a web interface to view and listen to that audio recording.

Someone enters their phone number and clicks the Call button on a webpage, Twilio initiates an outgoing call to that number, the caller to leaves a recorded message, the caller can then visit that webpage to play back the audio of that recorded message as an MP3.

This demo is written in PHP.

Concepts

This demo shows how to make outgoing calls using the Twilio REST API, how to use the TwiML <Record> verb to make an audio recording, how determine find the CallSid for a call and list recordings associated with that CallSid.

Try it

Visit http://demo.twilio.com/voicerecorder, enter your phone number, and click the Call button.

Implementation

Webserver
PHP
Places an outgoing call using the REST API Demos Steps 1 Phone picks up and Twilio sends CallSid Demos Steps 2 TwiML instructions to record audio Demos Steps 3 Twilio records the audio and plays it back Demos Steps 4 Request audio recordings for a CallSid using Twilio REST Demos Steps 5
Twilio

1

The index page is a simple form that accepts a phone number from the user.

index.php
<b>Twilio voice recorder demo</b>

<h2 style="color: #ff0000"><?php echo htmlentities($_REQUEST['msg']); ?></h2>

<h3>Please enter your phone number to leave voicemail
<form action="/voicerecorder/makecall.php" method="post">
    <input type="text" name="number" />
    <input type="submit" value="Call me to leave a voicemail">
</form>
</h3>

The user enters a phone number and presses the Call button. The browser requests the makecall.php page which makes a request to the Twilio REST URL /2008-08-01/Accounts/ACCCOUNT_SID/Calls (where ACCCOUNT_SID is your Twilio account identifier) which initiate an outgoing call.

To make the REST call we take advantage of the free PHP REST API library provided by Twilio. It simplified the the process of making HTTPS requests to Twilio and processing the responses. You can download a copy of the of the REST PHP libraries here. NOTE: If you would like to copy and use this code there are several account specific variables you will need to fill in including AccountSid, AuthToken, and CallerID. For more information on making outgoing calls take a look at the REST Quickstart.

makecall.php
<?php
require "twilio.php";

/* Twilio REST API version */
$ApiVersion = "2008-08-01";

/* Set our AccountSid and AuthToken */
$AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$AuthToken = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY";

/* Outgoing Caller ID you have previously validated with Twilio */
$CallerID = 'NNNNNNNNNN';

/* Instantiate a new Twilio Rest Client */
$client = new TwilioRestClient($AccountSid, $AuthToken);

if (!isset($_REQUEST['number'])) {
    $err = urlencode("Must specify phone number");
    header("Location: /voicerecorder/?msg=$err");
    die;
}

/* make Twilio REST request to initiate outgoing call */
$response = $client->request("/$ApiVersion/Accounts/$AccountSid/Calls",
    "POST", array(
        "Caller" => $CallerID,
        "Called" => $_REQUEST['number'],
        "Url" => "http://demo.twilio.com/voicerecorder/makerecording.php"
    ));
if($response->IsError) {
    $err = urlencode($response->ErrorMessage);
    header("Location: /voicerecorder/?msg=$err");
    die;
}

/* redirect back to the main page with CallSid */
$msg = urlencode("Calling... ".$_REQUEST['number'].
    ". Reload this page after leaving a recorded message.");
header("Location: /voicerecorder/?msg=$msg&CallSid=".
    $response->ResponseXml->Call->Sid);
?>

After completing the call, the server redirects the client back to the main page with the CallSid parameter set to the identifier of the outgoing call. When the Twilio REST API returns from a successful attempt to initiate an outgoing call, it returns a CallSid that uniquely identifies that call.

2

When the phone picks up, Twilio makes an HTTP request to the makerecording.php page the link to which was specified as part of the REST request. The CallSid parameter is passed back as part of this request.

3

When the phone picks up Twilio makes an HTTP request to the makerecording.php page the link to which was specified as part of the REST request. The makerecording page contains a TwiML <Say> verb and <Record> verb. The maxLength parameter tells Twilio to records a maximum of 30 seconds of audio.

makerecording.php
<?php header("content-type: text/xml"); ?>
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Hello. This is a call from the Twilio Voice Recorder demo.
         Please leave a recording after the beep.</Say>
    <Record action="/voicerecorder/playback.php" maxLength="30" />
</Response>

4

After Twilio executes the <Record> verb it stores the resulting audio and creates an entry for the recording in the Recording log associated with your Twilio account. The <Record> verb also takes an action handler which was specified as /voicerecorder/playback.php. After the caller hangs up or 5 seconds of silence elapses, Twilio will perform an HTTP POST or GET to the action handler with the RecordingUrl parameter containing the URL linking to the audio of the recording. In the Voice Recorder demo, the playback.php handler plays back the recording for the caller:

playback.php
<?php
    header("content-type: text/xml");
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
    <Say>Thanks for the message.  Here is what you recorded.</Say>
    <Play><?php echo $_REQUEST['RecordingUrl']; ?></Play>
    <Say>Goodbye.</Say>
</Response>

Click on this link to view the TwiML XML playback handler with an example RecordingUrl as Twilio does:

http://demo.twilio.com/voicerecorder/playback.php?RecordingUrl=http%3A//api.twilio.com/2008-08-01/Accounts/ACd8a7d2630000db3d04d40e3ea8604f80/Recordings/REa552f4683f93ed9655afc484dd14aeef.mp3

5

After clicking the Call Me button and the server initiating an outgoing call, the user is redirected back to the main page with CallSid as a GET URI parameter. Since the recording has most likely not completed yet the user will not see any recordings listed on the main page. However, if the user refreshes the main page after the recording is completed, her or she will see that recording listed on the main page.

The index.php page contains code that looks for the CallSid parameter in the request and if it exists queries looks for previous recordings associated with that CallSid using the Twilio REST API.

index.php
<?php
require "twilio.php";

/* Twilio REST API version */
$ApiServer = "api.twilio.com";
$ApiVersion = "2008-08-01";

/* Set our AccountSid and AuthToken */
$AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$AuthToken = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY";

/* Instantiate a new Twilio Rest Client */
$client = new TwilioRestClient($AccountSid, $AuthToken);

/* make Twilio REST request for a list of recordings for this CallSid */
if (isset($_REQUEST['CallSid'])) {
    $response = $client->request(
        "/$ApiVersion/Accounts/$AccountSid/Recordings", "GET",
        array('CallSid' => $_REQUEST['CallSid']));
    if($response->IsError) {
        echo "Error fetching recordings {$response->ErrorMessage}";
        die;
    }
}
?>

Any recordings returned by the Rest API are then listed in the main page.

index.php
<h3>Recording</h3>
<table border="1">
    <tr><th>Date</th><th>Duration</th></tr>
<?php
foreach($response->ResponseXml->Recordings->Recording AS $r) {
    echo "	<tr>\n";
    echo "		<td><a href=\"http://$ApiServer/$ApiVersion/Accounts/$AccountSid/Recordings/{$r->Sid}.mp3\">{$r->DateCreated}</td>\n";
    echo "		<td>{$r->Duration} seconds</td>\n";
    echo "	</tr>\n";
}
?>
</table>

The link to http://$ApiServer/$ApiVersion/Accounts/$AccountSid/Recordings/{$recording->Sid}.mp3 is a direct link to the audio recording. In this case a .mp3 extension was used so an MP3 file will be returned. Similarly, if a .wav extension was used then a WAV file would be returned.


There you have it. A simple voice recording system that integrates a web frontend with audio recording.

Demo files

Main web interface index.php
PHP code for initiating an outgoing call makecall.php
TwiML file for making a recording makerecording.php
TwiML file to play back the recording playback.php