这份文档还在翻译中,预期年底前完成。欢迎您提供宝贵的意见及建议。
Record a call
A code snippets that shows how to answer an incoming call and set it up to
record, then connect the call. When the call is completed, the eventUrl
you specify in the record
action of the NCCO will receive a webhook
including the URL of the recording for download.
Example
Replace the following variables in the example code:
Key | Description |
---|---|
VONAGE_NUMBER |
Your Vonage Number. E.g. 447700900000
|
TO_NUMBER |
The number you are calling. E.g. 447700900001
|
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 Call Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key
npm install express body-parser dotenv
Write the code
Add the following to record-a-call.js
:
require('dotenv').config({path: __dirname + '/../.env'})
const TO_NUMBER = process.env.TO_NUMBER
const VONAGE_NUMBER = process.env.VONAGE_NUMBER
const app = require('express')()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
const onInboundCall = (request, response) => {
const ncco = [{
action: "record",
eventUrl: [`${request.protocol}://${request.get('host')}/webhooks/recordings`]
},
{
action: "connect",
from: VONAGE_NUMBER,
endpoint: [{
type: "phone",
number: TO_NUMBER
}]
}
]
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)
Run your code
Save this file to your machine and run it:
node record-a-call.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 Call 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 RecordCall
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());
RecordAction record = RecordAction.builder().eventUrl(recordingUrl).build();
ConnectAction connect = ConnectAction.builder(PhoneEndpoint.builder(TO_NUMBER).build())
.from(VONAGE_NUMBER)
.build();
res.type("application/json");
return new Ncco(record, connect).toJson();
};
/*
* Route which prints out the recording URL it is given to stdout.
*/
Route recordingRoute = (req, res) -> {
System.out.println(RecordEvent.fromJson(req.body()).getUrl());
res.status(204);
return "";
};
Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/recordings", recordingRoute);
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 RecordCall
:
gradle run -Pmain=com.vonage.quickstart.voice.RecordCall
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 Call Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key
Install-Package Vonage
Create a file named RecordCallController.cs
and add the following code:
using Vonage.Voice.Nccos;
using Vonage.Voice.Nccos.Endpoints;
using Vonage.Voice.EventWebhooks;
using Newtonsoft.Json;
using System.IO;
using System.Text;
using Vonage.Utility;
Write the code
Add the following to RecordCallController.cs
:
[HttpGet("webhooks/answer")]
public IActionResult Answer()
{
var TO_NUMBER = Environment.GetEnvironmentVariable("TO_NUMBER") ?? "TO_NUMBER";
var VONAGE_NUMBER = Environment.GetEnvironmentVariable("VONAGE_NUMBER") ?? "VONAGE_NUMBER";
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 recordAction = new RecordAction()
{
EventUrl = new string[] { $"{sitebase}/recordcall/webhooks/recording" },
EventMethod = "POST"
};
var connectAction = new ConnectAction() { From = VONAGE_NUMBER, Endpoint = new[] { new PhoneEndpoint{ Number = TO_NUMBER } } };
var ncco = new Ncco(recordAction, connectAction);
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);
}
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 Call 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 Dotenv\Dotenv;
use Laminas\Diactoros\Response\JsonResponse;
use \Psr\Http\Message\ResponseInterface as Response;
use \Psr\Http\Message\ServerRequestInterface as Request;
Add the following to index.php
:
require 'vendor/autoload.php';
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
define('TO_NUMBER', getenv('TO_NUMBER'));
define('VONAGE_NUMBER', getenv('VONAGE_NUMBER'));
$app = new \Slim\App();
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->setEventWebhook(new \Vonage\Voice\Webhook($url));
$connect = new \Vonage\Voice\NCCO\Action\Connect(new \Vonage\Voice\Endpoint\Phone(TO_NUMBER));
$connect->setFrom(VONAGE_NUMBER);
$ncco = new \Vonage\Voice\NCCO\NCCO();
$ncco->addAction($connect);
$ncco->addAction($record);
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();
Run your code
Save this file to your machine and run it:
php index.php
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 Call 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-call.py
and add the following code:
from pprint import pprint
from flask import Flask, request, jsonify
app = Flask(__name__)
Write the code
Add the following to record-a-call.py
:
@app.route("/webhooks/answer")
def answer_call():
ncco = [
{
"action": "talk",
"text": "Hi, we will shortly forward your call. This call is recorded for quality assurance purposes."
},
{
"action": "record",
"eventUrl": ["https://demo.ngrok.io/webhooks/recordings"]
},
{
"action": "connect",
"eventUrl": ["https://demo.ngrok.io/webhooks/event"],
"from": "VONAGE_NUMBER",
"endpoint": [
{
"type": "phone",
"number": "RECIPIENT_NUMBER"
}
]
}
]
return jsonify(ncco)
@app.route("/webhooks/recordings", methods=['POST'])
def recordings():
data = request.get_json()
pprint(data)
return "webhook received"
if __name__ == '__main__':
app.run(port=3000)
Run your code
Save this file to your machine and run it:
python3 record-a-call.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 Call 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_call.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
Write the code
Add the following to record_a_call.rb
:
route :get, :post, '/webhooks/answer' do
[
{
"action": "record",
"eventUrl": ["#{request.base_url}/webhooks/recordings"]
},
{
"action": "connect",
"from": VONAGE_NUMBER,
"endpoint": [
{
"type": "phone",
"number": TO_NUMBER
}
]
}
].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
Run your code
Save this file to your machine and run it:
ruby record_a_call.rb
Try it out
You will need to:
- Answer and record the call (this code snippet).
- Download the recording. See the Download a recording code snippet for how to do this.