Record a call

    The Record API can record live calls at any time during the call and returns the URL of a file containing the audio recording. This API also lets you stop the recording at any point. The ability to initiate and stop recordings can be useful support and sales calls where reviews can help improve business processes.

    POST https://api.plivo.com/v1/Account/{auth_id}/Call/{call_uuid}/Record/


    In this tutorial, you will learn to build an app that when called, prompts the caller to “Press 1 to record this call”. Once the caller presses 1, the Record API will begin recording. Once the call is hung up, the Record API will return a URL of the recorded audio file. This app is preset to wait 7 seconds for the user to input “1” or the call will be hung up. In the event of an incorrect input, the app will return “Wrong Input”.

    Prerequisites

    1. Sign up for a free Plivo trial account.
    2. Check out our server-side SDKs page and install the right helper based on the programming language you want to use.
    3. A phone number is required to receive calls. You can buy a Plivo phone number in over 20+ countries through the Buy Numbers tab on your Plivo account UI. Check the Voice API coverage page for all the supported countries.
    4. Use a web hosting service to host your web application. There are many inexpensive cloud hosting providers that you can use for just a few dollars a month. Follow the instructions of your hosting provider to host your web application.

    Set up a Web Server

    Let’s assume your web server is located at myvoiceapp.com. Below is a snippet to set up a route on your webserver. Let’s call it, record_api. Now when we send an HTTP request to myvoiceapp.com/record_api this route will be invoked. This route will then return an XML that will read out a message for the caller and when 1 is pressed, which will invoke the record_api_action route and initiate the Record API. You will now have to configure this URL in your Plivo application.

    Note: For PHP, the route will be `myvoiceapp.com/record_api.php`
    1. Copy the relevant code below into a text file and save it. Let’s call it, record_api.
      Note: Make sure to use the appropriate file extention for your code (e.g., record_api.py for Python).
    2. Now that you have the code, you will need to expose your server to the public Internet. This way, Plivo will know where to find your app when a particular phone number is dialed. Moving forward, we will assume that your app is available at myvoiceapp.com.

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    
    import plivo, 
    from plivo import plivoxml
    from flask import Flask, Response, request, url_for
    
    app = Flask(__name__)
    
    # When the call is answered, a text is played which prompts the user to press 1 to record the call.
    # Once the digit is pressed, the Record API request is made and the recording starts.
    
    @app.route('/record_api/', methods=['POST', 'GET'])
    def record_api():
    
        response = plivoxml.ResponseElement()
        getinput_action_url = "http://www.foo.com/firstbranch/"
        response.add(plivoxml.GetInputElement().
            set_action('https://www.foo.com/result').
            set_method('POST').
            set_input_type('dtmf').
            set_digit_end_timeout(5).
            set_redirect(True).add(
                plivoxml.SpeakElement('Press 1 to record this call')))
        return Response(response.to_string(), mimetype='application/xml')
    
    # The Record API is invoked by the Get Digits action URL
    
    @app.route('/record_api_action/', methods=['POST', 'GET'])
    def record_action():
        digit = request.args.get('Digits')
        call_uuid = request.args.get('CallUUID')
        print "Call UUID is : %s " % (call_uuid)
        print "Digit pressed is : %s " % (digit)
    
        client = plivo.RestClient("Your AUTH_ID","Your AUTH_TOKEN")
        if digit == "1":
            response = client.calls.record(
                call_uuid=call_uuid, )
        else :
            print "Wrong Input"
            response = "Error"    
        return Response(response.to_string(), mimetype='text/plain')
    
    if __name__=='__main__':
        app.run(host='0.0.0.0',debug='True')
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    
    require 'rubygems'
    require 'sinatra'
    require 'plivo'
    
    include Plivo
    include Plivo::XML
    
    get '/record_api/' do
        r = Response.new()
    
        getinput_action_url = "https://example.com/record_api_action/"
        params = {
            action: getinput_action_url, 
            method: 'POST', 
            digitEndTimeout: '5',
            inputType:'dtmf',
            redirect:'true'
        }
        getinput = r.addGetInput(params)
        getinput.addSpeak("Press 1 to record this call")
    
        xml = PlivoXML.new(r)
        content_type "application/xml"
        return xml.to_s()
    end
    
    get '/record_api_action/' do
        digit = params[:Digits]
        call_uuid = params[:CallUUID]
    
        api = RestClient.new("YOUR_AUTH_ID", "YOUR_AUTH_TOKEN")
    
        if (digit == "1")
            response = api.calls.record(call_uuid)
            print response
        else
            print "Wrong Input"
        end
    end
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    
    var util = require('util');
    var express = require('express');
    var app = express();
    var plivo = require('plivo');
    
    app.set('port', (process.env.PORT || 5000));
    
    app.all('/record/', function (req, res) {
        var r = plivo.Response();
        var getinput_action_url, params, getDigits;
        getinput_action_url = req.protocol + '://' + req.headers.host + '/record/action/';
        params = {
            'action': getinput_action_url,
            'method': 'POST',
            'inputType': 'dtmf',
            'digitEndTimeout': '5',
            'redirect': 'true',
        };
        get_input = r.addGetInput(params);
        get_input.addSpeak("Press 1 to record this call");
    
        console.log(r.toXML());
        res.set({'Content-Type': 'text/xml'});
        res.send(r.toXML());
    });
    
    app.all('/record/action/', function (req, res) {
        // Plivo passes the digit captured by the xml produced by /record_api/ function as the parameter Digits
        var digit = req.param('Digits');
        // CallUUID parameter is automatically added by Plivo when processing the xml produced by /record_api/ function
        var call_uuid = req.param('CallUUID');
    
        var client = new plivo.Client("Your AUTH_ID","Your Auth_Token");
    
        if (digit === "1") {
            // Here we make the actual API call and store the response
            var response = client.calls.record(
            call_uuid, // call uuid
            )
            console.log(response);
        } else
            console.log("Wrong Input");
    });
    
    app.listen(app.get('port'), function() {
        console.log('Node app is running on port', app.get('port'));
    });
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    
    <!-- record_api.php -->
    
    <?php
        require 'vendor/autoload.php';
        use Plivo\XML\Response;
        $r = new Response();
        
        $getinput_action_url = "https://example.com/record_action.php";
        $get_input = $r->addGetInput([
                    'action' => $getinput_action_url,
                    'method' => "POST",
                    'digitEndTimeout' => "5",
                    'inputType' => "dtmf",
                    'redirect' => "true",
                ]);
        $get_input->addSpeak("Press 1 to record this call");
        Header('Content-type: text/xml');
        echo($r->toXML());
    ?>
    
    
    <!--record_action.php-->
    
    <?php
        require 'vendor/autoload.php';
        use Plivo\RestClient;
        use Plivo\Exceptions\PlivoRestException;
    
        $digit = $_REQUEST['Digits'];
        $uuid = $_REQUEST['CallUUID'];
        print("Digit : $digit");
        print("Call UUID : $uuid");
        $auth_id = "Your AUTH_ID";
        $auth_token = "Your AUTH_TOKEN";
        $client = new RestClient("YOUR_AUTH_ID", "YOUR_AUTH_TOKEN");
        if($digit == "1") {
            $response = $client->calls->startRecording($uuid);
            print("URL : {$response['response']['url']}");
            print("Recording ID : {$response['response']['recording_id']}");
            print("API ID : {$response['response']['api_id']}");
            print("Message : {$response['response']['message']}");
        } else {
            print("Wrong Input");
        }
    
    ?>
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    
    import static spark.Spark.*;
    import com.plivo.api.Plivo;
    import com.plivo.api.models.call.Call;
    import com.plivo.api.models.call.actions.CallRecordCreateResponse;
    import com.plivo.api.xml.GetInput;
    import com.plivo.api.xml.Response;
    import com.plivo.api.xml.Speak;
    
    public class recordcall {
        public static void main(String[] args) {
            post("/record/", (request, response) -> {
                response.type("application/xml");
                Response resp = new Response();
                resp.children(
                        new GetInput()
                                .action("https://www.foo.com/record/action/")
                                .method("POST")
                                .inputType("dtmf")
                                .digitEndTimeout(5)
                                .redirect(true)
                                .children(
                                        new Speak("Press 1 to record this call")
                                )
                );
                return resp.toXmlString();
            });
            post("/record/action/", (request, response) -> {
                response.type("application/json");
                String digit = request.queryParams("Digits");
                String call_uuid = request.queryParams("CallUUID");
                System.out.println("Digit : " + digit + " Call UUID : " + call_uuid);
                response.raw().getWriter().print("Digit : " + digit + " Call UUID : " + call_uuid);
                Response resp = new Response();
    
                Plivo.init("Your AUTH_ID","Your AUTH_TOKEN");
                if(digit.equals("1")) {
                    CallRecordCreateResponse r = Call.recorder(call_uuid)
                            .record();
                    System.out.println(r);
                } else {
                    System.out.println("Wrong Input");
                }
                return "ok";
            });
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    
    package main
    
    import (
    	"fmt"
    	"github.com/go-martini/martini"
    	"github.com/plivo/plivo-go/xml"
    	"github.com/plivo/plivo-go"
    	"net/http"
    )
    
    func main() {
    	m := martini.Classic()
    	m.Post("/record/", func(w http.ResponseWriter, r *http.Request) string {
    		w.Header().Set("Content-Type", "application/xml")
    		response := xml.ResponseElement{
    			Contents: []interface{}{
    				new(xml.GetInputElement).
    				SetAction("https://www.foo.com/record/action/").
    				SetMethod("POST").
    				SetDigitEndTimeout(5).
    				SetInputType("dtmf").
    				SetRedirect(true).
    				SetContents([]interface{}{new(xml.SpeakElement).
    					SetContents("Press 1 to record this call"),
    					}),
    			},
    		}
    		return response.String()
    	})
    	m.Post("/record/action/", func(w http.ResponseWriter, r *http.Request) string {
    		digits := r.FormValue("Digits")
    		uuid := r.FormValue("CallUUID")
    		fmt.Printf("Digit received: %#v\n", digits)
    		client, err := plivo.NewClient("", "", &plivo.ClientOptions{})
    		if err != nil {
    			panic(err)
    		}
    		response, err := client.Calls.Record(
    			uuid,
    			plivo.CallRecordParams{},
    		)
    		fmt.Printf("Response: %#v\n", response)
    		return "ok"
    	})
    	m.Run()
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using Microsoft.AspNetCore.Mvc;
    using Plivo;
    using Plivo.XML;
    
    // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
    
    namespace Recordcall.Controllers
    {
        public class RecordController : Controller
        {
            // GET: /<controller>/
            public IActionResult Index()
            {
                var resp = new Response();
                Plivo.XML.GetInput get_input = new
                    Plivo.XML.GetInput("",
                        new Dictionary<string, string>()
                        {
                            {"action", "https://www.foo.com/record/action/"},
                            {"method", "POST"},
                            {"digitEndTimeout", "5"},
                            {"finishOnKey", "#"},
                            {"inputType", "dtmf"},
                            {"redirect", "false"},
                        });
                resp.Add(get_input);
                get_input.AddSpeak("Press 1 to record this call",
                    new Dictionary<string, string>() { });
                var output = resp.ToString();
                return this.Content(output, "text/xml");
            }
            // Action URL
            public String Action()
            {
                String digits = Request.Query["Digits"];
                String uuid = Request.Query["CallUUID"];
                Debug.WriteLine("Digit pressed : {0}, Call UUID : {1}", digits, uuid);
    
                if (digits == "1")
                {
                    string auth_id = "Your AUTH_ID";
                    string auth_token = "Your AUTH_TOKEN";
                    var api = new PlivoApi(auth_id, auth_token);
    
                    var resp = api.Call.StartRecording(
                        callUuid: uuid
                    );
    
                    Debug.WriteLine(resp);
                }
                else
                {
                    Debug.WriteLine("Invalid");
                }
                
                return "OK";
            }
        }
    }
    

    Create an Application

    1. Create an Application by visiting the Application Page and click on New Application or by using Plivo’s Application API.
    2. Give your application a name. Let’s call it Record Call. Enter your server URL (e.g., http://www.myvoiceapp.com/record_api) in the Answer URL field and set the method as POST. See our Application API docs to learn how to modify your application through our APIs.
    3. Click on Create to save your application.

    Plivo Create Application

    Assign a Plivo number to your app

    1. Navigate to the Numbers page and select the phone number you want to use for this app.
    2. Select Record Call (name of the app) from the Plivo App dropdown list.
    3. Click on Update to save.

    Create Text to Speech Application

    If you don’t have a number, go to the Buy Number page to purchase a Plivo phone number.

    Voice Phone Number Search

    Test and validate

    When you call the Plivo phone number you assigned to this app, Plivo will answer and say “Press 1 to record this call”. Plivo will then wait a maximum of 7 seconds for the user to press 1. Once the caller presses 1, the Record API will begin recording. Once the call is hung up, the Record API will return a URL of the recorded audio file.

    Sample XML

    <Response>
        <GetInput action="https://www.foo.com/record/action/" method="POST" digitEndTimeout="5" inputType="dtmf" redirect="true">
            <Speak>Press 1 to record this call</Speak>
        </GetInput>
        <Wait length="10"/>
    </Response>

    Sample Response

    Digit : 1 Call UUID is : 2a2875b6-9592-11e4-8b35-cd90edc77fa9
    
    (202, {
            u'url': u'http://s3.amazonaws.com/recordings_2013/67673232-9594-11e4-baad-842b2b17453e.mp3',
            u'recording_id': u'16963644-9594-11e4-baad-842b2b17453e',
            u'message': u'call recording started',
            u'api_id': u'16847e54-9594-11e4-b423-22000ac8a2f8'
        }
    )