Record a call with split audio
A code snippet that shows how to answer an incoming call and set it up to record the conversation legs separately, 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.
Prerequisites
Create an Application
You can install the CLI with the following command:
Before you can start working with your apps, you need to register your configuration: API Key and Secret. You can find them via the Dashboard, in API Settings. Once set, initialize your account using the following command:
As soon as the CLI is both installed and configured, use it to create a Vonage application using the following command:
The command starts an interactive prompt to ask for the application name, and the capabilities you want to enable - make sure to enable Voice.
When finished, it creates the vonage_app.json file in the current directory containing the Application ID, Application name and private key. It also creates a second file with the private key name app_name.key.
Go to the Application's page on the Dashboard, and define a Name for your Application.

Make sure to click on the Generate public and private key button, and keep the file private.key around.
Then, enable the Voice capability. For the moment, leave everything by default.

Finally, click Save at the bottom of the page.
Rent a Number
You can rent a number using the Vonage CLI. The following command purchases an available number in the United States:
Specify an alternative two-character country code to purchase a number in another country.
In the Dashboard, go to the Buy Numbers page. Make sure to tick Voice in the search filter, and select the country you want to buy a number in.

You can then click the Buy button next to the number you want, and validate your purchase.
Congratulations! Your virtual number is now listed in Your Numbers
Link a Number
Now that you have both an application and a number, you need to link them together.
Replace YOUR_VONAGE_NUMBER with the number you bought and APPLICATION_ID with your application id, then run the following command:
Now that you have both an application and a number, you need to link them together.
Go to the Application page, and click on the application you created earlier.

In the Voice section, click on the Link button next to the number you want to link.
Example
Replace the following variables in the example code:
| Key | Description |
|---|---|
VONAGE_NUMBER | Your Vonage Number. E.g. |
TO_NUMBER | The number you are calling. E.g. |
Prerequisites
npm install express body-parserWrite the code
Add the following to record-a-call-with-split-audio.js:
const Express = require('express');
const bodyParser = require('body-parser');
const app = new Express();
app.use(bodyParser.json());
const onInboundCall = (request, response) => {
const ncco = [
{
action: 'record',
split: 'conversation',
channels: 2,
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:
Prerequisites
Add the following to build.gradle:
implementation 'com.vonage:server-sdk-kotlin:1.1.2'
implementation 'io.ktor:ktor-server-netty'
implementation 'io.ktor:ktor-serialization-jackson'Write the code
Add the following to the main method of the RecordCallSplitAudio file:
embeddedServer(Netty, port = 8000) {
routing {
get("/webhooks/answer") {
call.response.header("Content-Type", "application/json")
call.respond(
Ncco(
recordAction {
eventUrl(call.request.path().replace("answer", "recordings"))
channels(2)
split(SplitRecording.CONVERSATION)
},
connectToPstn(TO_NUMBER) {
from(VONAGE_NUMBER)
}
).toJson()
)
}
post("/webhooks/recordings") {
val event = EventWebhook.fromJson(call.receive())
println("Recording URL: ${event.recordingUrl}")
call.respond(204)
}
}
}.start(wait = true)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.kt.voice with the package containing RecordCallSplitAudio:
Prerequisites
Add the following to build.gradle:
implementation 'com.vonage:server-sdk:8.15.1'
implementation 'com.sparkjava:spark-core:2.9.4'Write the code
Add the following to the main method of the RecordCallSplitAudio file:
/*
* 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)
.channels(2)
.split(SplitRecording.CONVERSATION)
.build();
ConnectAction connect = ConnectAction.builder(PhoneEndpoint.builder(TO_NUMBER).build())
.from(VONAGE_NUMBER)
.build();
res.type("application/json");
return new Ncco(record, connect);
};
/*
* Route which prints out the recording URL it is given to stdout.
*/
Route recordingRoute = (req, res) -> {
System.out.println(EventWebhook.fromJson(req.body()).getRecordingUrl());
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 RecordCallSplitAudio:
Prerequisites
Install-Package VonageWrite the code
Add the following to SplitAudioController.cs:
[HttpGet("webhooks/answer")]
public IActionResult Answer()
{
var toNumber = Environment.GetEnvironmentVariable("TO_NUMBER") ?? "TO_NUMBER";
var vonageNumber = 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 eventUrl = $"{Request.Scheme}://{host}/SplitAudio/webhooks/recording";
var talkAction = new TalkAction {Text = "recording call", BargeIn = false};
var recordAction = new RecordAction
{
EventUrl = new[] {eventUrl},
EventMethod = "POST",
Channels = 2,
Split = "conversation"
};
var connectAction = new ConnectAction()
{
From = vonageNumber,
Endpoint = new[] {new PhoneEndpoint {Number = toNumber}},
};
var ncco = new Ncco(talkAction, 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
composer require slim/slim:^3.8 vonage/clientWrite the code
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();
$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));
$record->setChannels(2);
$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:
Prerequisites
pip install 'flask>=1.0'Write the code
Add the following to record-a-call-with-split-audio.py:
from pprint import pprint
from flask import Flask, request, jsonify
app = Flask(__name__)
@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",
"split": "conversation",
"channels": 2,
"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"
Run your code
Save this file to your machine and run it:
Prerequisites
gem install sinatra sinatra-contribWrite the code
Add the following to record-a-call-with-split-audio.rb:
before do
content_type :json
end
helpers do
def parsed_body
JSON.parse(request.body.read)
end
end
route :get, :post, '/webhooks/answer' do
[
{
"action": "record",
"split": "conversation",
"channels": 2,
"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, 3000Run your code
Save this file to your machine and run it:
Try it out
You will need to:
- Answer and record the call with split audio (this code snippet).
- Download the recording. See the Download a recording code snippet for how to do this.