SIGN UP

Handling an incoming call

Handling an incoming call

This tutorial explains how to call the Voximplant cloud from a phone or SDK endpoint, such as a website or mobile app. The cloud answers the call with a text-to-speech greeting. You can use the below example as a basis for a smart answering machine or as a part of a more elaborate solution with call forwarding to a call center or SDK endpoints.

Prepare a project

You need to register at our website and create a new application as described in the previous tutorial. If you want to call from a mobile or landline phone, you should rent a phone number (you should rent a virtual phone number for debugging). If you want to make calls from a web page or mobile device, select the appropriate SDK and create a new project.

You can use the Voximplant Web SDK on any HTML page. Note that due to the security reasons, the underlying WebRTC technology can work only if it’s loaded from a web server (not from a file). So, if you want to use a plain HTML instead of a server-enabled framework, make sure to load it from some sort of server. For this tutorial, create an index.html file, execute the following code to start a local server and open http://localhost:8080 in a web browser:
yarn add live-server
yarn run live-server​
Create a new Android Studio project.
Install CocoaPods and follow the next step on creating a new XCode project and adding Voximplant iOS SDK as a dependency.

Add SDK to the project

Our native and cross-platform SDK follows the best practices of the target endpoint platform. Select the appropriate SDK below and follow the instructions on how to add it to your project.

The minified version of the web SDK is available from our CDN. Add the following link to your web page to connect the SDK and a global Voximplant object to it:
<script type="text/javascript" src="//cdn.voximplant.com/edge/voximplant.min.js"></script>​
Modify the Android Studio project's build.gradle config file to include the Voximplant SDK
dependencies {
  // Add this line with the latest version number from the SDK changelog
  implementation 'com.voximplant:voximplant-sdk:2.3.5'
  ...
}​
The Voximplant iOS SDK uses CocoaPods for dependency management. After CocoaPods is installed, create the Podfile and install dependencies via the following commands:
target 'TargetName' do
  use_frameworks!
  pod 'VoxImplantSDK', '2.12.0'
  post_install do |installer|
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings['ENABLE_BITCODE'] = 'NO'
      end
    end
  end
end​

After dependencies are installed, open the generated .xcworkspace file in the XCode. Include the NSMicrophoneUsageDescription and the NSCameraUsageDescription keys in your app's Info.plist file and provide reasonable strings for these keys. Declare four "Background Modes" via the XCode interface: "Audio and AirPlay", "Background fetch", "Remote notifications" and "Voice over IP".

Initialize the SDK

You should initialize the Voximplant SDK before you can use it.
Many operations are ASYNCHRONOUS
Many Voximplant SDK operations are asynchronous. You need to use a platform-specific way to continue executing your code after such an operation ends. Depending on the platform, it can be a callback, promise, etc.
 
const sdk = VoxImplant.getInstance();
sdk.init()
  .then(() => {
    // This code is executed after SDK successfully initializes
  });
IClient client = Voximplant.getClientInstance(
  Executors.newSingleThreadExecutor(),
  getApplicationContext(),
  new ClientConfig());
VIClient *client = [[VIClient alloc]
  initWithDelegateQueue:dispatch_get_main_queue()];

Connect SDK to the Voximplant cloud

In order to accept and initiate calls, Voximplant SDK needs to be connected to the Voximplant cloud via a persistent TCP connection.

sdk.connect().then(() => {
    // This code is executed after SDK is successfully connected to Voximplant
  })
  .catch(() => {
    // This code is executed in case of error (no network etc)
});
// implement 'IClientSessionListener'

// Sample entry point
public void connect() {
  client.setClientSessionListener(this);
  client.connect();
}

@Override
public void onConnectionEstablished() {
  // This code is executed after SDK is successfully connected to Voximplant
}

@Override
public void onConnectionFailed(String error) {
  // This code is executed in case of error (no network etc)
}
// Implement 'VIClientSessionDelegate'

- (instancetype)init {
  ...
  self.client.sessionDelegate = self;
  [self.client connect];
  ...
}

- (void)clientSessionDidConnect:(VIClient *)client {
  // This code is executed after SDK is successfully connected to Voximplant
}

- (void)client:(VIClient *) client
        sessionDidFailConnectWithError:(NSError *)error {
  // This code is executed in case of error (no network etc)
}

Configure the SDK to log in to the Voximplant cloud

To distinguish between different SDKs connected to the Voximplant cloud, each SDK should log in to the cloud using the Voximplant user credentials. Depending on your goal, you can configure the SDKs so that all instances log in as one Voximplant user or you can use different credentials for each instance. The Voximplant user credentials can be created programmatically via the Voximplant HTTP API.
 
USE A FULL USERNAME AND ADD THE USER TO THE VOXIMPLANT APP
Voximplant requires fully-qualified credentials to select which application will handle the call. A login attempt will fail if the specified user was not assigned to the specified application in the Voximplant control panel.
sdk.login("username@appname.accname.voximplant.com", "pass")
  .then(() => {
    // This code is executed on successfull login
  })
  .catch(() => {
    // This code is executed on error (wrong name, pass etc)
  });
// Implement 'IClientLoginListener'

@Override
public void onConnectionEstablished() {
  // Login after SDK is connected to the Voximplant cloud
  client.setClientLoginListener(this);
  client.login("username@appname.accname.voximplant.com", "pass");
}

@Override
public void onLoginSuccessful(String displayName, AuthParams authParams) {
  // This code is executed on successfull login
}

@Override
public void onLoginFailed(LoginError loginError) {
  // This code is executed on error (wrong name, pass etc)
}
- (void)clientSessionDidConnect:(VIClient *)client {
  // Login after SDK is connected to the Voximplant cloud
  [client
    loginWithUser:@"username@appname.accname.voximplant.com"
         password:@"pass"
          success:^(NSString *displayName, NSDictionary *authParams) {
            // This code is executed on successfull login
          }
          failure:^(NSError *error) {
            // This code is executed on error (wrong name, pass etc)
          }];
}

Initiate a call to the Voximplant cloud

Voximplant support calls from any endpoint to the cloud and from the cloud to any endpoint. This way, a traditional phone-to-phone call is split into two call legs: from the first phone (or SDK) to the Voximplant cloud and from the Voximplant cloud to the second phone (or SDK), with the audio streams from both calls connected to each other via a cloud-based JavaScript code. This tutorial demonstrates a simple one-leg case where an SDK endpoint calls the Voximplant cloud, and the cloud generates an audio stream via the built-in text-to-speech conversion engine.
SPECIFY A PHONE NUMBER EVEN IF IT'S NOT USED
When calling the Voximplant cloud from the endpoint, you should specify a "phone number to call". If you don’t use a traditional pass-through, such as forwardCallToPSTN, you can specify any non-empty string for it.
const call = sdk.call("*");
// Implement 'ICallListener'

@Override
public void onLoginSuccessful(String displayName, AuthParams authParams) {
  boolean isVideo = false;
  String customData = null;
  VideoFlags videoFlags = new VideoFlags(isVideo, isVideo);
  ICall call = client.callTo("*", videoFlags, customData);
  call.addCallListener(this);
  Map<String, String> headers = null;
  call.start(headers);
}
// Implement 'VICallDelegate'

// Sample method to initiate a call
- (void)call {
  VICall *call = [client callToUser:@"*"
                      withSendVideo:NO
                       receiveVideo:NO
                         customData:nil];
  [call addDelegate:self];
  [call startWithHeaders:nil];
}

Handle call events

The Voximplant SDK is asynchronous: you subscribe to events like "connected" or "disconnected", and the SDK will execute the specified callbacks.
call.on(VoxImplant.CallEvents.Connected, () => console.log("You can hear audio from the cloud"));
call.on(VoxImplant.CallEvents.Disconnected, () => console.log("The call has ended"));
// Implement 'ICallListener' and set object as a listener, which is
// demonstrated in the previous step

@Override
public void onCallConnected(ICall call, Map<String, String> headers) {
  // You can hear audio from the cloud
}

@Override
public void onCallDisconnected(ICall call, Map<String, String> headers, boolean answeredElsewhere) {
  // The call has ended
}
// Implement 'VICallDelegate' and set object as a delegate, which is
// demonstrated in the previous step

- (void)call:(VICall *)call didConnectWithHeaders:(NSDictionary *)headers {
  // You can hear audio from the cloud
}

- (void)call:(VICall *)call 
        didDisconnectWithHeaders:(NSDictionary *)headers
               answeredElsewhere:(NSNumber *)answeredElsewhere {
  // The call has ended
}

Cloud-side JavaScript scenario

Modify your cloud-side JavaScript application so that it will answer an incoming call and synthesize speech. Note that your SDK endpoint should be logged in with a correct username and app name and that the specified user should be assigned to the specified app in the control panel. Use the call log for debugging.
VoxEngine.addEventListener(AppEvents.CallAlerting, function(e) {
  // this code is executed in the cloud on every incoming call
  e.call.startEarlyMedia();
  e.call.say("hello from the cloud", Language.US_ENGLISH_FEMALE);
});

Testing out

To test the created application, open the index.html page in your web browser. After some time you will hear a synthesized voice from the Voximplant cloud. In case of errors, check the browser developer console log first and then the Voximplant JavaScript session log.

Next: initiating an outgoing call

read more >>>
Get your free developer account or talk with our sales team to learn more about Voximplant solutions
SIGN UP
Contact sales

Please complete this field.

Please complete this field.

Please complete this field.

Choose the solution

Please complete this field.

Please complete this field.