分割音声で通話を録音
着信に応答し、次のように設定する方法を示すコード・スニペット。
通話を接続する。通話が完了すると
が完了すると eventUrl で指定した record NCCOのアクション
のアクションは、ダウンロード用の録画URLを含むウェブフックを受け取ります。
例
サンプルコードの以下の変数を置き換える:
| キー | 説明 |
|---|---|
VONAGE_VIRTUAL_NUMBER | Your Vonage Number. E.g. |
VOICE_TO_NUMBER | The recipient number to call, 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_VIRTUAL_NUMBER,
endpoint: [
{
type: 'phone',
number: VOICE_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(port, () => {
console.log(`Example app listening on port ${port}`);
});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:2.1.1'
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 class:
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)
},
connectToPstn(VOICE_TO_NUMBER) {
from(VONAGE_VIRTUAL_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 アプリケーション 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:9.3.1'
implementation 'com.sparkjava:spark-core:2.9.4'Write the code
Add the following to the main method of the RecordCallSplitAudio 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)
.channels(2)
.build();
ConnectAction connect = ConnectAction.builder(PhoneEndpoint.builder(VOICE_TO_NUMBER).build())
.from(VONAGE_VIRTUAL_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 アプリケーション 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 VOICE_TO_NUMBER = Environment.GetEnvironmentVariable("VOICE_TO_NUMBER") ?? "VOICE_TO_NUMBER";
var VONAGE_VIRTUAL_NUMBER = Environment.GetEnvironmentVariable("VONAGE_VIRTUAL_NUMBER") ?? "VONAGE_VIRTUAL_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 = VONAGE_VIRTUAL_NUMBER,
Endpoint = new[] {new PhoneEndpoint {Number = VOICE_TO_NUMBER}},
};
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/clientRun your code
Save this file to your machine and run it:
Prerequisites
pip install vonage python-dotenv fastapi[standard]Write the code
Add the following to record-a-call-with-split-audio.py:
import os
from os.path import dirname, join
from pprint import pprint
from dotenv import load_dotenv
from fastapi import Body, FastAPI
from vonage_voice import Connect, NccoAction, PhoneEndpoint, Record
dotenv_path = join(dirname(__file__), '../.env')
load_dotenv(dotenv_path)
VONAGE_VIRTUAL_NUMBER = os.environ.get('VONAGE_VIRTUAL_NUMBER')
VOICE_TO_NUMBER = os.environ.get('VOICE_TO_NUMBER')
app = FastAPI()
@app.get('/webhooks/answer')
async def inbound_call():
ncco: list[NccoAction] = [
Record(
split='conversation',
channels=2,
eventUrl=['https://demo.ngrok.io/webhooks/recordings'],
),
Connect(
from_=VONAGE_VIRTUAL_NUMBER, endpoint=[PhoneEndpoint(number=VOICE_TO_NUMBER)]
),
]
return [step.model_dump(by_alias=True, exclude_none=True) for step in ncco]
@app.post('/webhooks/recordings')
async def recordings(data: dict = Body(...)):
pprint(data)
return {'message': 'webhook received'}Run your code
Save this file to your machine and run it:
Prerequisites
gem install sinatra sinatra-contribRun your code
Save this file to your machine and run it:
試してみる
必要なのは
- 通話に応答し、音声を分割して録音する(このコードスニペット)。
- 録画をダウンロードするを見る 録音をダウンロードする のコード・スニペットで説明している。