Skip to main content

Twilio - Record a complete incoming call


    Currently, Twilio services does not provide to record the whole incoming call. Only dial initiated within the incoming call can be recorded. But in day to day life, there are many occasion we need to record the whole incoming call such as an ivr call or a customer service call. So, by taking the twilio feature that child call can be recorded, i have developed a call flow using two twilio numbers so that we can record the complete call from caller.

For demonstrating, i have created a small ivr. When caller calls twilio number. It will be asked a gather "whether he/she is interested in taking to our agent? if yes press one or not press two or just hangup". If caller press one, call will be redirected to an agent.

Traditional twilio call route. We get recording of just agent call.

If we try above call method, we get only the recording of agent call. We misses what happened after twilio answer and before agent call. So to get whole call recording, i have developed another mechanism as below

New call route to record the complete call.

When caller calls twilio number A, twilio will answer and executes the voice url. In its voice url, we will dial another twilio number B which has another voice url. In this voice url, we will gather option from caller. If he press 1, we will redirect incoming call leg to another url and from there we will dial our agent.

For example, Let first twilio number be A and second twilio number be B. Let us set voice url of A be www.your-domain.com/twilio-complete-call-record/incoming.php and status callback url be www.your-domain.com/twilio-complete-call-record/status_callback.php. Also set voice url for B be www.your-domain.com/twilio-complete-call-record/call_handler_one.php

When caller calls A, incoming.php is executed. In this, dial B with call_handler_status_callback.php as action url and record-from-ringing as record value.

echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<Response>';
echo '<Dial action="call_handler_status_callback.php" record="record-from-ringing">';
echo '<Number>'.$twilio_redirect_num.'</Number>'; // twilior edirect number is number B
echo '</Dial>';
echo '</Response>';

When B answers, call_handler_one.php is executed.

echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<Response>';
echo '<Gather action="gather_handler.php" numDigits="1" timeout="10">';
echo '<Say voice="woman">If you like to talk to our agent please press one. Or not, press two or just hangup this call.</Say>';
echo '</Gather>';
echo '</Response>';

When caller enters any digit, gather_handler.php is executed. If caller enters one, we need to dial agent.

echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<Response>';
if($_REQUEST["Digits"]=="1")
{
echo '<Say voice="woman">Please hold while we tranfer our call to out agent.</Say>';
$client = new Twilio\Rest\Client($twilio_sid, $twilio_token);
$call= $client->account->calls->get($_REQUEST['parentCallSid']);
$call->update(array(
"Url" => "call_handler_two.php",
"Method" => "POST"
));
}
else
{
echo '<Hangup />';
}
}
echo '</Response>';

using twilio rest client api, we will redirect incoming call leg to call_handler_two.php. So now we will get recording for our first call leg in call_handler_status_callback.php.

Now in call_handler_two.php, we will dial our agent with same call_handler_status_callback.php as action url and record-from-ringing as record value.

echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<Response>';
echo '<Dial action="call_handler_status_callback.php" record="record-from-ringing">';
echo '<Number>'.$agent_number.'</Number>';
echo '</Dial>';
echo '</Response>';

When this call is completed, call_handler_status_callback.php is executed again. Here's the script code.

$call_temp_file = $temp_path."/".$_REQUEST["CallSid"].".txt"; // $temp_path is the complete path to a temp directory
if(!file_exists($call_temp_file))
{
file_put_contents($call_temp_file, json_encode(array("recording_url_1" = > $_REQUEST["RecordingUrl"]))); // writes recording url of first call.
}
else
{
$call_recording_urls = json_decode(file_get_contents($call_temp_file), true);
$call_recording_urls["recording_url_2"] = $_REQUEST["RecordingUrl"]; // add recording url for second call.
file_put_contents($call_temp_file, json_encode($call_recording_urls));
}
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<Response>';
echo '</Response>';

When whole call is completed, status call back url of number A is executed. In this script, we will concatenate these two recordings to one and save in another directory.

$call_temp_file = $temp_path."/".$_REQUEST["CallSid"].".txt";

if(file_exists($call_temp_file))
{
$recording_urls = json_decode($call_temp_file, true); // get call recording urls
$merge_audio_name = "";
$recording_list = array();
foreach ($recording_urls as $key => $value)
{
$filename=array_pop(explode("/",$value));
$temp_file_name = $temp_path."/".$filename.".wav";
exec("wget -O $temp_file_name $value.wav"); // download recodings from twilio to local server.
if(file_exists($temp_file_name))
{
$recording_list[] = $temp_file_name;
$merge_audio_name .= $filename;
}
}
if(count($recording_list)==1)
{
exec("mv ".$recording_list[0]." ".$recordings_path."/"); // recording_path is the complete path to for directory to save recordings.
}
else if(count($recording_list)>1)
{
$merge_audio_name .= ".wav";
$cmd = "sox ";
foreach ($recording_list as $key => $value)
{
$cmd .= $value." ";
}
$cmd .= $recordings_path."/".$merge_audio_name;
exec($cmd); // concatenate two leg recordings to one
foreach ($recording_list as $key => $value)
{
unlink($value);
}
}
}

Now call recording will be in recordings folder. You can download this sample project from https://github.com/ijasnahamed/twilio-complete-call-record

Popular posts from this blog

Implementing Client Side WebRTC using Sipml5 javascript

Step 1:

Download and require Sipml5 library function.

Step 2:

Initialize sipml5 Engine in your web page :

var readyCallback = function(e) {
// function called when sipml is successfully initialised.
createSipStack(); // calling this function to create sip stack(see below)
};

var errorCallback = function(e) {
// function called when error occured during sipml initialisation.
};

SIPml.init(readyCallback, errorCallback);

Step 3:

Create Sip Stack :-
Sip Stack is an object that must be created before making/receiving call and sms. Creating Sip stack is an asynchronous process, so you need to create an event listener function to get state change notification.

var sipStack;

function EventListener(e) {

/*
* e.type ;type of event listener
* e.session ; current event session
* e.getSipResponseCode() ; event response code
* e.description ; event description
*/

if(e.type == 'started'){
// successfully started the stack.
register();
} else if(e.type == 'i_new_call'){
// when new incoming call comes.
      …

Setup Asterisk 13 with FreePBX 13 in CentOS 7

Launch CentOS 7 AWS Ec2 InstanceLog in to your aws consoleGo to ec2 management page and click Launch Instance on Instance pageIn Choose AMI step, go to AWS MarketPlace tab and search CentOS 7 on search field. List of centos 7 ami's will be available.Select CentOS 7 (x86_64) ami which is free tier eligible. Select your instance type and click configure instance. Keep default values from Configure Instance to Add Tags stepsIn configure security group, create a security group which allow minimum ports openSSH : port 22HTTP : port 80Custom UDP Rule : 10000-20000 (if you are giving RTP ports 10000-20000)Custom UDP Rule : 5060 (ChanSIP port)Custom TCP Rule : 5060 (ChanSIP Port)Click Launch Instance. Select your key file and accept terms to launch instance.
Setup CentOS Server SSH into newly created CentOS server with username centos and your key file.Update all existing packagessudo yum update -yNow start http service(you can access your server via browser by going to your server ip addres…

MULTIPLE FILE UPLOAD USING AJAX WITH PROGRESS BAR

Uploading multiple files using ajax makes a pleasant feeling to the user. It makes even more happier if upload progress status is printed with percentage.

            In this blog, you will make a file upload form using ajax with file upload progress bar.

Prerequisites :

1) Javascript supported browser
2) LAMP Server / XAMPP Server

Code :

index.html

<!DOCTYPE html>
<html> <head><title>Multiple File Upload using Ajax</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script> </head> <body><div><form action="action.php" method="post" enctype="multipart/form-data" id="multiple-upload-form"><input type="button" id="select-file-btn" value="Select Files" onclick="document.getElementById('files').click(); return false;&qu…