
シェア:
スタンダップ・コメディーの学位論文を持つ俳優の訓練を受け、ミートアップ・シーンを経てPHP開発に携わるようになった。技術について話したり書いたり、レコード・コレクションから変わったレコードを再生したり買ったりしています。
Play an Audio File Into a Voice Call With PHP
所要時間:9 分
Every time I phone my local leisure center to book a swimming session, I’m greeted with an announcement of the latest news: the center is closed for two hours next Monday, the timetable for the family swim has changed, etc. In this article, I’ll show you an example of how they do this with Vonage’s Voice API and a PHP backend written in the Slim Framework to play audio into an ongoing phone call.
Prerequisites
Firstly, we need a new Slim application. I’m going to make this as absolutely vanilla as possible - no big boilerplates, no automatic templating. We’re going to have one endpoint that will trigger an outbound call, and one incoming endpoint to read the webhook generated when the end user picks up a call.
Create a directory that will contain our code, and then use Composer to generate a new project:
composer initYou can skip all interactive questions by hitting return, which will use defaults. When asked if you want to add packages interactively, make sure you refuse; this is so I can show the commands in this article to pull in the framework.
Composer will generate its configuration file composer.json, and a dependency folder, vendor. The default settings will also create the directory that will house your code, src.
In the command line, we’ll need to pull the Slim framework in and a PSR-7 interface for the request/response classes. The final command will pull in the Vonage PHP SDK, which handles all the heavy lifting to make API requests for you. Lastly, our Vonage Client is configured with environment variables, so we’ll need the de facto library to handle that.
composer require slim/slim slim/psr7 vonage/client vlucas/phpdotenvNow that we have Slim and our other required dependencies, we can start writing the application. The Vonage PHP SDK requires an Application ID and a Private Key, both of which you get when creating a new application instance on the Vonage Dashboard. Alternatively, you can do this using the Vonage CLI, which is the route we’re going to take.
Install and Configure the Vonage CLI
Install the Vonage CLI globally using the following command:
npm install @vonage/cli -gThen, configure the CLI with your Vonage API key and secret, which you will find in the Developer Dashboard:
vonage auth set \
--api-key='VONAGE_API_KEY' \
--api-secret='VONAGE_API_SECRET'Replace the VONAGE_API_KEY and VONAGE_API_SECRET with your details to authenticate the CLI.
API設定ページを開く API設定ページを開き、Vonage API KeyとSecretにアクセスしてください。両者は以下のスクリーンショットのように表示されます。APIキーはページの上部にあり、APIシークレットにアクセスするには、"Account secret "サブセクションを参照してください。
注:以前に作成したAPIシークレットを覚えていない場合は、"+ Create new secret "をクリックし、安全に保存してください。

You can validate your authentication to make sure everything is working using the following command:
vonage auth checkIf you have installed the CLI in your local project rather than globally, you can add an extra flag to check:
vonage auth check --localバーチャル電話番号を購入するには APIダッシュボードにアクセスし、以下の手順に従ってください。
Purchase a phone number
あなたの APIダッシュボード
BUILD & MANAGE > Numbers > Buy Numbersを開きます。
必要な属性を選択し、検索をクリックします。
ご希望の番号の横にある購入ボタンをクリックし、購入を確定する。
バーチャルナンバーを購入したことを確認するには、左側のナビゲーションメニューの「BUILD & MANAGE」から「Numbers」、「Your Numbers」の順にクリックします。
Create the Voice Application
To use the Voice API, you must create a Voice API application. This is not the same thing as the web application you are building. It is merely a container for the configuration and security information you need to connect to Vonage's APIs.
vonage apps create 'Play audio app' \
--private-key-file="$HOME/private.key"You will receive the following (example, dummy) data to note down:
Name: play audio app
Application ID: 7a319bf9-49e7-413d-914b-402fe8e68XXX
Improve AI: Off
Private/Public Key: Set
You’ll notice that we have given the command the argument of private-key-file. This will download your private key for you once the command has executed: locate this key file (in the command, I have used the UNIX-like ~/ location, which is the home folder; you’ll want to set it to something like C:\Users\YOUR-USER-NAME if you are using Powershell in Windows) and place the file in the root directory of your project.
We have not set the application to use the Voice API yet, so run the following command to add the Voice capability:
vonage apps capabilities update "$VONAGE_APPLICATION_ID" voice \
--voice-answer-url='https://example.com/webhooks/answer' \
--voice-event-url='https://example.com/webhooks/event'Link the purchased number to the application. Buying a number does not link it automatically, and the number must support Voice:
vonage apps numbers link "$VONAGE_APPLICATION_ID" "$VONAGE_NUMBER"You will notice that we are setting the voice-answer-url and the voice-event-url at the application level here. These are placeholders for now, and you do not need to change these values. The reason here is that the code used to make the call will dynamically create these during the HTTP calls that are made.
Because you should never put secrets into your codebase, create a new file in the root of your project named .env. Populate the variables with the corresponding information, the TO_NUMBER being the number that the dialler calls. We’ll get onto the BASE_URL later. The VONAGE_APPLICATION_PRIVATE_KEY_PATH can be left as is in the example below, and the VONAGE_NUMBER should be a purchased Vonage Virtual Number that has been purchased in the Dashboard.
VONAGE_APPLICATION_ID=your-application-id
VONAGE_APPLICATION_PRIVATE_KEY_PATH=private.key
VONAGE_NUMBER=447700900000
TO_NUMBER=447700900001
BASE_URL=https://your-public-tunnel.exampleIn the src directory, create a new file, index.php, and add the following code:
<?php
declare(strict_types=1);
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Vonage\Client\Credentials\Keypair;
use Vonage\Voice\Endpoint\Phone;
use Vonage\Voice\NCCO\NCCO;
use Vonage\Voice\NCCO\Action\Stream;
use Vonage\Voice\NCCO\Action\Talk;
use Vonage\Voice\OutboundCall;
use Vonage\Voice\Webhook;
require_once __DIR__ . '/../vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();
$app = AppFactory::create();
$app->addBodyParsingMiddleware();
$app->post('/dial', function (
Request $request,
Response $response
): Response {
$privateKeyPath = realpath(
__DIR__ . '/../' . $_ENV['VONAGE_APPLICATION_PRIVATE_KEY_PATH']
);
if ($privateKeyPath === false) {
throw new RuntimeException('Vonage private key file was not found.');
}
$privateKey = file_get_contents($privateKeyPath);
if ($privateKey === false) {
throw new RuntimeException('Vonage private key file could not be read.');
}
$credentials = new Keypair(
$privateKey,
$_ENV['VONAGE_APPLICATION_ID']
);
$client = new \Vonage\Client($credentials);
$call = new OutboundCall(
new Phone($_ENV['TO_NUMBER']),
new Phone($_ENV['VONAGE_NUMBER'])
);
$call
->setAnswerWebhook(
new Webhook(
$_ENV['BASE_URL'] . '/webhooks/answer',
Webhook::METHOD_POST
)
)
->setEventWebhook(
new Webhook(
$_ENV['BASE_URL'] . '/webhooks/event',
Webhook::METHOD_POST
)
);
$client->voice()->createOutboundCall($call);
$response->getBody()->write('Outbound call started');
return $response;
});
$app->post('/webhooks/answer', function (
Request $request,
Response $response
): Response {
$ncco = new NCCO();
$ncco->addAction(
new Talk('Here is some soothing music for you')
);
$ncco->addAction(
new Stream($_ENV['BASE_URL'] . '/audio.mp3')
);
$response->getBody()->write(
json_encode($ncco->jsonSerialize(), JSON_THROW_ON_ERROR)
);
return $response->withHeader(
'Content-Type',
'application/json'
);
});
$app->post('/webhooks/event', function (
Request $request,
Response $response
): Response {
$payload = $request->getParsedBody();
error_log(json_encode($payload, JSON_THROW_ON_ERROR));
return $response->withStatus(204);
});
$app->run();There’s a lot going on here, so let’s break it down. The application enables Slim body parsing so getParsedBody() can read the event payload. The event webhook logs the payload and returns HTTP 204 because it has no response body.
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();This code loads the contents of the .env file into the PHP superglobal $_ENV array to set up our Vonage Client. $app = AppFactory::create() creates a new Slim application instance, so we can then set up our endpoints.
Our outbound dialer is defined as an HTTP POST route, /dial. Using POST avoids creating a phone call as a side effect of a browser, crawler, or link preview issuing a GET request.
$privateKeyPath = realpath(
__DIR__ . '/../' . $_ENV['VONAGE_APPLICATION_PRIVATE_KEY_PATH']
);
if ($privateKeyPath === false) {
throw new RuntimeException('Vonage private key file was not found.');
}
$privateKey = file_get_contents($privateKeyPath);
if ($privateKey === false) {
throw new RuntimeException('Vonage private key file could not be read.');
}
$credentials = new Keypair(
$privateKey,
$_ENV['VONAGE_APPLICATION_ID']
);
$client = new \Vonage\Client($credentials);The PHP SDK uses the application private key and application ID to create a JWT for the authenticated Voice API request that starts the call. Incoming Voice webhooks are separate HTTP requests from Vonage. In production, enable signed callbacks and verify them so your application can confirm that the request came from Vonage and was not modified in transit.
It is possible for a Vonage Application to be configured within the Dashboard to always hit the same Answer URL and the same Event URL for ongoing application updates. However, as you can see from the code used, you can also dynamically set these webhook endpoints. This would be useful when you have instances of several different workflows and are tracking the progress of individual calls. For example, you can add a database table that can then do CRUD-style operations with a UUID in the URL path. This gives you the flexibility to handle multiple queries at once, if you use something like Route Model Binding with Laravel Octane. Our Slim code is a bit simpler for readability:
$call = new OutboundCall(
new Phone($_ENV['TO_NUMBER']),
new Phone($_ENV['VONAGE_NUMBER'])
);
$call
->setAnswerWebhook(
new Webhook(
$_ENV['BASE_URL'] . '/webhooks/answer',
Webhook::METHOD_POST
)
)
->setEventWebhook(
new Webhook(
$_ENV['BASE_URL'] . '/webhooks/event',
Webhook::METHOD_POST
)
);
$client->voice()->createOutboundCall($call);
$response->getBody()->write('Outbound call started');
return $response;The Webhook path is configured by using the environment variable BASE_URL. Now we have the outbound call path, we’ll need to define what that BASE_URL is.
You’ll need to serve the application locally first. To make things as simple as possible, we’ll use the built-in server in PHP. Navigate to the src directory and then fire it up:
php -S localhost:8080Our Webhooks are POST requests coming directly from Vonage. So, without exposing our application to the Internet, there’s no way Vonage can get to our localhost application. The most commonly used tool to expose it would be Ngrok, which you can find installation instructions here. If you want to keep it strictly PHP, you can use Beyond Code’s Expose, which leverages the power of an event loop provided by ReactPHP. The important action is to run one of these tools and note down the URL you get back. From there, you paste it into the BASE_URL in the .env file and hey presto! A way of consuming incoming data.
Our last part of the execution code takes that data, announces that sound is coming, and then plays the sound.
$app->post('/webhooks/answer', function (
Request $request,
Response $response
): Response {
$ncco = new NCCO();
$ncco->addAction(
new Talk('Here is some soothing music for you')
);
$ncco->addAction(
new Stream($_ENV['BASE_URL'] . '/audio.mp3')
);
$response->getBody()->write(
json_encode($ncco->jsonSerialize(), JSON_THROW_ON_ERROR)
);
return $response->withHeader(
'Content-Type',
'application/json'
);
});This code returns an NCCO to Vonage. The Talk action announces that audio is coming, and the Stream action plays the file from the public URL in BASE_URL. The Stream URL must be reachable from the public internet; localhost URLs will not work for Vonage. Use a supported MP3 or WAV file and encoding. Vonage support guidance notes that MP3 files should contain an ID3 header. The corrected example uses audio.mp3 consistently.
You’re all set: send a POST request to your public URL’s /dial endpoint. The Vonage platform will call the answer webhook, receive the NCCO, and stream audio into the call.
Audio file requirements
The URL passed to Stream must be reachable from the public internet. For local development, expose the PHP server with an HTTPS tunnel and set BASE_URL to the tunnel URL. The stream action supports a single MP3 or WAV URL, but unsupported audio encoding can prevent playback. Keep the filename consistent with the code: the corrected example uses audio.mp3.
Conclusion
In this post, you learned how to play audio into an existing call and about the NCCO actions that govern the call flow. Feel free to experiment by substituting different audio files and NCCO actions. The following resources might help:
ご質問がある場合、またはあなたが作っているものを共有したい場合は、こちらをクリックしてください。
登録する 開発者ニュースレター
フォローする X(旧ツイッター)最新情報
Videoの方がいいですか? 当社の YouTubeチャンネルでチュートリアルをご覧ください
LinkedInの LinkedIn の Vonage デベロッパーページ
開発者体験の向上にご協力ください。以下の 「開発者の声」フィードバックにご協力ください
最新の開発者向けニュース、ヒント、イベント情報をお届けします。