这份文档还在翻译中,预期年底前完成。欢迎您提供宝贵的意见及建议。

Record a message

A code snippet that shows how to record a conversation. Answer an incoming call and return an NCCO that includes a record action. When the call is complete, a webhook is sent to the eventUrl you specify. The webhook includes the URL of the recording.

Example

Prerequisites

A Vonage 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 Vonage 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 Vonage 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

Vonage 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/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

npm install express body-parser

Write the code

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

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 #. We will get back to you as soon as we can.'
    },
    {
      action: 'record',
      endOnKey: '#',
      beepStart: 'true',
      endOnSilence: "3",
      eventUrl: [
        `${request.protocol}://${request.get('host')}/webhooks/recordings`
      ]
    },
    {
      action: 'talk',
      text: 'Thank you for your message. Goodbye.'
    }
  ]

  response.json(ncco)
}

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

  response.status(204).send()
}

app
  .get('/webhooks/answer', onInboundCall)
  .post('/webhooks/recordings', onRecording)

app.listen(3000)

View full source

Run your code

Save this file to your machine and run it:

node record-a-message.js

Prerequisites

A Vonage 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 Vonage 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 Vonage 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

Vonage 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/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

Add the following to `build.gradle`:

compile 'com.vonage:client:5.5.0'
compile 'com.sparkjava:spark-core:2.7.2'

Write the code

Add the following to the main method of the RecordMessage class:

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

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

    RecordAction record = RecordAction.builder()
            .eventUrl(recordingUrl)
            .endOnSilence(3)
            .endOnKey('#')
            .beepStart(true)
            .build();

    TalkAction outro = TalkAction.builder("Thank you for your message. Goodbye").build();

    res.type("application/json");

    return new Ncco(intro, record, outro).toJson();
};

/*
 * Route which prints out the recording URL it is given to stdout.
 */
Route recordingRoute = (req, res) -> {
    RecordEvent recordEvent = RecordEvent.fromJson(req.body());
    System.out.println(recordEvent.getUrl());

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

Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/recordings", recordingRoute);

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.vonage.quickstart.voice with the package containing RecordMessage:

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

Prerequisites

A Vonage 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 Vonage 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 Vonage 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

Vonage 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/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

Install-Package Vonage

Create a file named RecordMessageController.cs and add the following code:

using Vonage.Utility;
using Vonage.Voice.EventWebhooks;
using Vonage.Voice.Nccos;

View full source

Write the code

Add the following to RecordMessageController.cs:

[HttpGet("webhooks/answer")]
public IActionResult Answer()
{
    var host = Request.Host.ToString();
    //Uncomment the next line if using ngrok with --host-header option
    //host = Request.Headers["X-Original-Host"];
    var sitebase = $"{Request.Scheme}://{host}";
    var outGoingAction = new TalkAction() { Text = "Please leave a message after the tone, then press #. We will get back to you as soon as we can" };            
    var recordAction = new RecordAction()
    {
        EventUrl = new string[] { $"{sitebase}/recordmessage/webhooks/recording" },
        EventMethod = "POST",
        EndOnSilence = "3",
        EndOnKey = "#",
        BeepStart="true"
    };
    var thankYouAction = new TalkAction { Text = "Thank you for your message. Goodbye" };
    var ncco = new Ncco(outGoingAction, recordAction, thankYouAction);
    return Ok(ncco.ToString());
}

[HttpPost("webhooks/recording")]
public async Task<IActionResult> Recording()
{
    var record = await WebhookParser.ParseWebhookAsync<Record>(Request.Body, Request.ContentType);
    Console.WriteLine($"Record event received on webhook - URL: {record?.RecordingUrl}");
    return StatusCode(204);
}

View full source

Prerequisites

A Vonage 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 Vonage 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 Vonage 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

Vonage 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/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

composer require slim/slim:^3.8 vonage/client

Create a file named index.php and add the following code:

use Laminas\Diactoros\Response\JsonResponse;
use \Psr\Http\Message\ResponseInterface as Response;
use \Psr\Http\Message\ServerRequestInterface as Request;

View full source

Add the following to index.php:

require 'vendor/autoload.php';

$app = new \Slim\App();

View full source

Write the code

Add the following to index.php:

$app->get('/webhooks/answer', function (Request $request, Response $response) {
    //Get our public URL for this route
    $uri = $request->getUri();
    $url = $uri->getScheme() . '://'.$uri->getHost() . ($uri->getPort() ? ':'.$uri->getPort() : '') . '/webhooks/recording';

    $record = new \Vonage\Voice\NCCO\Action\Record();
    $record
        ->setEndOnSilence(3)
        ->setEndOnKey('#')
        ->setBeepStart(true)
        ->setEventWebhook(new \Vonage\Voice\Webhook($url))
    ;

    $ncco = new \Vonage\Voice\NCCO\NCCO();
    $ncco
        ->addAction(
            new \Vonage\Voice\NCCO\Action\Talk('Please leave a message after the tone, then press #. We will get back to you as soon as we can')
        )
        ->addAction($record)
        ->addAction(
            new \Vonage\Voice\NCCO\Action\Talk('Thank you for your message. Goodbye')
        )
    ;

    return new JsonResponse($ncco);
});

$app->post('/webhooks/recording', function (Request $request, Response $response) {
    /** @var \Vonage\Voice\Webhook\Record */
    $recording = \Vonage\Voice\Webhook\Factory::createFromRequest($request);
    error_log($recording->getRecordingUrl());

    return $response->withStatus(204);
});

$app->run();

View full source

Run your code

Save this file to your machine and run it:

php -S localhost:3000 -t .

Prerequisites

A Vonage 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 Vonage 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 Vonage 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

Vonage 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/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

pip install 'flask>=1.0'

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

from pprint import pprint
import http
from flask import Flask, request, jsonify

app = Flask(__name__)

View full source

Write the code

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

@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)


if __name__ == '__main__':
    app.run(port=3000)

View full source

Run your code

Save this file to your machine and run it:

python3 record-a-message.py

Prerequisites

A Vonage 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 Vonage 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 Vonage 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

Vonage 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/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

gem install sinatra sinatra-contrib

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

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:

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 Vonage Number, and leaving your message after the tone (this code snippet).
  2. Download the recording. See the Download a recording code snippet for how to do this.