Record a message

A building block that shows how to record a message.

Example

Prerequisites

Create an application

A Nexmo application contains the required configuration for your project. You can create an application using the Nexmo CLI  (see below) or via the dashboard  . To learn more about applications see our Nexmo concepts guide.

Install the CLI

$ npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Nexmo application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Nexmo needs to connect to your local machine to access your answer_url. We recommend using ngrok  to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

$ nexmo app:create "Record Message Example"  http://demo.ngrok.io/webhooks/events --keyfile private.key
Install dependencies

$ npm install express body-parser

Write the code

Add the following to app.js:

Copy to Clipboard
const app = require('express')()
const bodyParser = require('body-parser')

app.use(bodyParser.json())

const onInboundCall = (request, response) => {
  const ncco = [
    {
      action: 'talk',
      text: 'Please leave a message after the tone, then press pound.'
    },
    {
      action: 'record',
      endOnKey : '#',
      beepStart: 'true',
      eventUrl: [
        `${request.protocol}://${request.get('host')}/webhooks/recording`
      ]
    },
    {
      action: 'talk',
      text: 'Thank you for your message.'
    }
  ]

  response.json(ncco)
}

const onRecording = (request, response) => {
  const recording_url = request.body.recording_url
  console.log(`Recording URL = ${recording_url}`)

  response.status(204).send()
}

View full source 

Run your code

Save this file to your machine and run it:

$ node app.js

Prerequisites

Create an application

A Nexmo application contains the required configuration for your project. You can create an application using the Nexmo CLI  (see below) or via the dashboard  . To learn more about applications see our Nexmo concepts guide.

Install the CLI

$ npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Nexmo application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Nexmo needs to connect to your local machine to access your answer_url. We recommend using ngrok  to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

$ nexmo app:create "Record Message Example"  http://demo.ngrok.io/webhooks/events --keyfile private.key
Install dependencies

Add the following to build.gradle:

compile 'com.nexmo:client:latest.release'
compile 'com.sparkjava:spark-core:2.7.2'

Write the code

Add the following to RecordMessage.java:

Copy to Clipboard
/*
 * Route to answer and connect incoming calls with rec.ording.
 */
Route answerRoute = (req, res) -> {
    String recordingUrl = String.format("%s://%s/webhooks/recordings", req.scheme(), req.host());

    TalkNcco intro = new TalkNcco(
            "Please leave a message after the tone, then press #. We will get back to you as soon as we can.");

    RecordNcco record = new RecordNcco();
    record.setEventUrl(recordingUrl);
    record.setEndOnSilence(3);
    record.setEndOnKey('#');
    record.setBeepStart(true);

    TalkNcco outro = new TalkNcco("Thank you for your message. Goodbye");

    Ncco[] nccos = new Ncco[]{intro, record, outro};

    res.type("application/json");

    // com.fasterxml.jackson.databind.ObjectMapper;
    return new ObjectMapper().writer().writeValueAsString(nccos);
};

/*
 * Webhook Route which prints out the recording URL it is given to stdout.
 */
Route recordingRoute = (req, res) -> {
    System.out.println(RecordingPayload.fromJson(req.bodyAsBytes()).getRecordingUrl());

    res.status(204);
    return "";
};

Spark.port(3000);

View full source 

Run your code

We can use the application plugin for Gradle to simplify the running of our application. Update your build.gradle with the following:

apply plugin: 'application'
mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

Run the following gradle command to execute your application, replacing com.nexmo.quickstart.voice with the package containing RecordMessage:

gradle run -Pmain=com.nexmo.quickstart.voice.RecordMessage

Prerequisites

Create an application

A Nexmo application contains the required configuration for your project. You can create an application using the Nexmo CLI  (see below) or via the dashboard  . To learn more about applications see our Nexmo concepts guide.

Install the CLI

$ npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Nexmo application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Nexmo needs to connect to your local machine to access your answer_url. We recommend using ngrok  to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

$ nexmo app:create "Record Message Example"  http://demo.ngrok.io/webhooks/events --keyfile private.key
Install dependencies

$ composer require slim/slim:^3.8

Write the code

Add the following to index.php:

Copy to Clipboard
$app = new \Slim\App;

$app->get('/webhooks/answer', function (Request $request, Response $response) {
    $uri = $request->getUri();
    $ncco = [
        [
            'action' => 'talk',
            'text' => 'Please leave a message after the tone, then press #. We will get back to you as soon as we can'

        ],
        [
            'action' => 'record',
            'eventUrl' => [
                $uri->getScheme().'://'.$uri->getHost().':'.$uri->getPort().'/webhooks/recording'
            ],
            'endOnSilence' => '3',
            'endOnKey' => '#',
            'beepOnStart' => true
        ],
        [
            'action' => 'talk',
            'text' => 'Thank you for your message. Goodbye'
        ],

    ];

    return $response->withJson($ncco);
});

$app->post('/webhooks/recording', function (Request $request, Response $response) {
    $params = $request->getParsedBody();
    error_log($params['recording_url']);
    return $response->withStatus(204);
});

$app->run();

View full source 

Run your code

Save this file to your machine and run it:

$ php -t . -S localhost:3000

Prerequisites

Create an application

A Nexmo application contains the required configuration for your project. You can create an application using the Nexmo CLI  (see below) or via the dashboard  . To learn more about applications see our Nexmo concepts guide.

Install the CLI

$ npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Nexmo application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Nexmo needs to connect to your local machine to access your answer_url. We recommend using ngrok  to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

$ nexmo app:create "Record Message Example"  http://demo.ngrok.io/webhooks/events --keyfile private.key
Install dependencies

$ pip install 'flask>=1.0'
Initialize your dependencies

Create a file named record-a-message.py and add the following code:

Copy to Clipboard
import http
from pprint import pprint

from flask import Flask, request, jsonify

app = Flask(__name__)

View full source 

Write the code

Add the following to record-a-message.py:

Copy to Clipboard
@app.route("/webhooks/answer")
def answer_call():
    for param_key, param_value in request.args.items():
        print("{}: {}".format(param_key, param_value))
    recording_webhook_url = request.url_root + "webhooks/recording"
    ncco =[
        {
            "action": "talk",
            "text": "Please leave a message after the tone, then press the hash key."
        },
        {
            "action": "record",
            "endOnKey": "#",
            "beepStart": "true",
            "eventUrl": [recording_webhook_url]
        },
        {
            "action": "talk",
            "text": "Thank you for your message."
        }
    ])
    return jsonify(ncco)


@app.route("/webhooks/recording", methods=['POST'])
def recording_webhook():
    pprint(request.get_json())
    return ('', http.HTTPStatus.NO_CONTENT)

View full source 

Run your code

Save this file to your machine and run it:

$ python3 record-a-message.py

Prerequisites

Create an application

A Nexmo application contains the required configuration for your project. You can create an application using the Nexmo CLI  (see below) or via the dashboard  . To learn more about applications see our Nexmo concepts guide.

Install the CLI

$ npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Nexmo application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Nexmo needs to connect to your local machine to access your answer_url. We recommend using ngrok  to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

$ nexmo app:create "Record Message Example"  http://demo.ngrok.io/webhooks/events --keyfile private.key
Install dependencies

$ gem install sinatra
Initialize your dependencies

Create a file named record-a-message.rb and add the following code:

Copy to Clipboard
require 'sinatra'
require 'sinatra/multi_route'
require 'json'

before do
  content_type :json
end

helpers do
  def parsed_body
    JSON.parse(request.body.read)
  end
end

View full source 

Write the code

Add the following to record-a-message.rb:

Copy to Clipboard
route :get, :post, '/webhooks/answer' do
    [
        {
            "action": "talk",
            "text": "Please leave a message after the tone, then press #. We will get back to you as soon as we can"
        },
        {
            "action": "record",
            "eventUrl": ["#{request.base_url}/webhooks/recordings"],
            "endOnSilence": "3",
            "endOnKey": "#",
            "beepStart": "true"
        },
        {
            "action": "talk",
            "text": "Thank you for your message. Goodbye"
        }
      ].to_json
end

route :get, :post, '/webhooks/recordings' do
  recording_url = params['recording_url'] || parsed_body['recording_url']
  puts "Recording URL = #{recording_url}"

  halt 204
end

set :port, 3000

View full source 

Run your code

Save this file to your machine and run it:

$ ruby record-a-message.rb

Try it out

You will need to:

  1. Record a message by dialling your Nexmo Number, and leaving your message after the tone (this building block).
  2. Download the recording. See the 'Download a recording' building block for how to do this.