right  Talk To Us!

Cloud UAS Sample Quickstart

UAS API - Quickstart Sample Application

  • Filename:

    samples/quickstart.py

    Description:

    An inbound application that is provided as the default target application for the inbound developer service. It rings the call for 2 seconds, answers the call, then reads out the decoded pincode and username from the called address before hanging up.

    The main() function of the Python code is executed by the UAS when an incoming call is detected. This function receives a number of parameters.

    Parameter NameDescription
    channel Provides access to the call and media control API
    application_instance_id provides a unique ID for this instance of the application
    file_man provides access to the file management API
    my_log provides a reference to the UAS logger
    application_parameters provides access to the parameter string set on the inbound service page

    The application extracts the information that it wants to say from the channel.Details.call_to parameter and uses the function channel.FilePlayer.say() to speak it using Text-To-Speech technology. The caller may hangup at any time, in which case most of the channel functions will raise a Hangup exception. Applications should always catch any exceptions in a try and except block, just as this sample code does. At the end of the application, the logger is used to write a completed message.

    Code:

    """
        An inbound application that is provided as the default target application for the inbound developer service. 
        It rings the call for 2 seconds, answers the call, then reads out the decoded pincode and username from the called address before hanging up. 
    """
    
    __uas_identify__ = "application"
    __uas_version__ = "1.0b3"
    
    import sys, os
    from prosody.uas import Hangup, Error
    
    SIP_PREFIX = "sip:"
    PINCODE_PREFIX = "--"
    PINCODE_LEN = 8
    
    # Speak the pin code as separate digits.
    def get_tts_str_from_pincode(pincode):
        ttsstr = ', '.join(list(pincode))
        return ttsstr
    
    # Get suitable string for TTS based on SIP username in supplied call_to.
    # The SIP username must start with "sip:".
    # If next characters are "--" and the remaining 8 digits are numeric then read as a pin code.
    def get_tts_str_from_username(my_log, log_pref, call_to):
        # check we have a sane call_to
        splat = call_to.split("@")
        if len(splat) != 2:
            return "an unknown SIP username"
        if not splat[0].startswith(SIP_PREFIX):
            return "an unknown SIP username"
        username = splat[0][len(SIP_PREFIX):]
        # if we have a pin code, try to speak it nicely
        if username.startswith(PINCODE_PREFIX):
            pincode = username[len(PINCODE_PREFIX):]
            try:
                int(pincode)
            except ValueError:
                pincode = ""
            if len(pincode) == PINCODE_LEN:
                my_log.info("{0} username [{1}] pincode [{2}]".format(log_pref, username, pincode))
                tts_str = get_tts_str_from_pincode(pincode)
                return "user pin code{0}".format(tts_str)
        # otherwise, just return the username
        my_log.info("{0} username [{1}]".format(log_pref, username))
        return "SIP username {0}".format(username)
    
    def main(channel, application_instance_id, file_man, my_log, application_parameters):
        return_code = 0
        log_pref = "quickstart:"
        call_to = channel.Details.call_to
        my_log.info("{0} started with call_to [{1}]".format(log_pref, call_to))
        tts_str = get_tts_str_from_username(my_log, log_pref, call_to)
        try:
            channel.ring(2)
            channel.answer()
            channel.FilePlayer.say("Hello, this is the quick start application for {0}. Have a good day. Goodbye.".format(tts_str))
            channel.hang_up()
            
        except Hangup as exc:
            my_log.info("{0} completed with Hangup".format(log_pref))
    
        except Error as exc:
            my_log.exception("{0} completed with Error exception! {1}".format(log_pref, exc))
            return_code = -101
    
        except Exception as exc:
            my_log.exception("{0} completed with exception! {1}".format(log_pref, exc))
            return_code = -102
    
        my_log.info("{0} completed".format(log_pref))
        return return_code
    
  • Filename:

    Samples\C#\QuickStart\QuickStart.cs

    Description:

    The C# application code is initiated via the Run() method that is called by the UAS. Arguments supplied to this method are the UASCallChannel with which SIP and PSTN calls are controlled and an applicationParameters string. This string is specified in the Inbound Service that was invoked and resulted in this application being run.

    The UASCallChannel class contains a property CallDetails which provides information associated with a call. The CallTo property is the destination address of the inbound call. This is manipulated by the GetTtsFromUsername method to decode the pincode/username.

    We simulate the phone ringing for four seconds with channel.Ring(4) and then answer the call with channel.Answer(). channel.FilePlayer provides a way of playing wav files and also to convert text into audio speach which can then be played to a call. The Say() method uses Text-To-Speech (TTS) to produce audio data.

    The caller may hangup at any time, in which case the channel.State property will go to Idle. Notice that we can use the Trace property of the application's base class to log application information e.g. this.Trace.TraceInfo("some log info").

    Code:

    using System;
    using System.Threading;
    using AMSClassLibrary;
    using UASAppAPI;
    
    // A simple inbound application that rings the call for 4 seconds, answers the call, then 
    // reads out the decoded pincode and username from the callTo parameter before hanging up.
    namespace QuickStart
    {
        // The application class.
        // This must have the same name as the assembly and must inherit from either 
        // UASInboundApplication or UASOutboundApplication.
        // It must override the Run method.
        public class QuickStart : UASInboundApplication
        {
            // Possible return codes
            enum ReturnCode
            {
                // Success Codes:
                Success = 0,
                // ... any positive integer
    
                // Fail Codes:
                // -1 to -99 reserved
                ExceptionThrown = -100
            }
    
            const string sipPrefix = "sip:";
            const string pincodePrefix = "--";
            const int pinCodeLength = 8;
    
            // This is the entry point for the application
            public override int Run(UASCallChannel channel,
                                    string applicationParameters)
            {
                this.Trace.TraceInfo("Start - appParms [{0}]", applicationParameters);
                ReturnCode reply = ReturnCode.Success;
    
                try
                {
                    string callTo = channel.CallDetails.CallTo;
                    this.Trace.TraceInfo("Call started with callTo [{0}]", callTo);
    
                    // Decode the pincode/username from the callTo
                    string tts = GetTtsFromUsername(callTo);
                    channel.Ring(4);
                    channel.Answer();
    
                    // Say it back to caller
                    channel.FilePlayer.Say(
                        "Hello, this is the quick start application for {0}. Have a good day. Goodbye.", tts);
                }
                catch (Exception e)
                {
                    this.Trace.TraceError("Exception thrown {0}", e.Message);
                    reply = ReturnCode.ExceptionThrown;
                }
                finally
                {
                    channel.HangUp();
                }
    
                this.Trace.TraceInfo("Completed with return code {0}", reply);
                return (int)reply;
            }
    
            // Convert the pin code to comma-separated digits.
            private string GetTtsFromPinCode(string pinCode)
            {
                string tts = "";
                foreach (char c in pinCode)
                {
                    if (tts.Length > 0) {
                        tts += ", ";
                    }
                    tts += c;
                }
                return tts;
            }
    
            // Get suitable string for TTS based on SIP username in supplied callTo.
            // The SIP username must start with "sip:".
            // If next characters are "--" and the remaining 8 digits are numeric then read as a pin code.
            private string GetTtsFromUsername(string callTo)
            {
                // check we have a sane callTo
                string[] splits = callTo.Split(new char[] {'@'});
                if (splits.Length != 2)
                {
                    return "an invalid SIP username";
                }
                if (!splits[0].StartsWith(sipPrefix))
                {
                    return "an invalid SIP username";
                }
    
                // Remove the Sip:
                string username = splits[0].Substring(sipPrefix.Length);
                
                // If we have a pin code, try to say it nicely.
                if (username.StartsWith(pincodePrefix))
                {
                    string pinCode = username.Substring(pincodePrefix.Length); 
    
                    // Is it the right length
                    if (pinCode.Length != pinCodeLength)
                    {
                        return "a pin code that is not of length " + pinCodeLength;
                    }
    
                    try
                    {
                        int pinCodeValue = Convert.ToInt32(pinCode);
                    }
                    catch (Exception)
                    {
                        return "an invalid pin code";
                    }
    
                    this.Trace.TraceInfo("Username [{0}] pincode [{1}]", username, pinCode);
                    return "user pin code " + GetTtsFromPinCode(pinCode);
                }
    
                // Otherwise, just return the username
                this.Trace.TraceInfo("Username [{0}]", username);
                return "SIP username " + username;
            }
        }
    }
    
  • Filename:

    Samples\VB\QuickStart\QuickStart.vb

    Description:

    The Visual Basic application code is initiated via the Run() method that is called by the UAS. Arguments supplied to this method are the UASCallChannel with which SIP and PSTN calls are controlled and an applicationParameters string. This string is specified in the Inbound Service that was invoked and resulted in this application being run.

    The UASCallChannel class contains a property CallDetails which provides information associated with a call. The CallTo property is the destination address of the inbound call. This is manipulated by the GetTtsFromUsername method to decode the pincode/username.

    We simulate the phone ringing for four seconds with channel.Ring(4) and then answer the call with channel.Answer(). channel.FilePlayer provides a way of playing wav files and also to convert text into audio speach which can then be played to a call. The Say() method uses Text-To-Speech (TTS) to produce audio data.

    The caller may hangup at any time, in which case the channel.State property will go to Idle. Notice that we can use the Trace property of the application's base class to log application information e.g. Me.Trace.TraceInfo("some log info").

    Code:

    Imports AMSClassLibrary
    Imports UASAppAPI
    
    ' A simple inbound application that is provided as the default Developer Service Target Entry.
    ' It rings the call for 4 seconds, answers the call, then reads out the decoded pincode 
    ' and username from the callTo parameter before hanging up.
    Namespace QuickStart
    
        ' The application class.
        ' This must have the same name as the assembly and must inherit from either 
        ' UASInboundApplication or UASOutboundApplication.
        ' It must override the Run method.
        Public Class QuickStart
            Inherits UASInboundApplication
    
            ' Possible return codes
            Enum ReturnCode
                ' Success Codes:
                Success = 0
                ' ... any positive integer
    
                ' Fail Codes:
                ' -1 to -99 reserved
                ExceptionThrown = -100
            End Enum
    
            ' Some features of the developer pin code
            Const sipPrefix = "sip:"
            Const pincodePrefix = "--"
            Const pinCodeLength = 8
    
            ' This is the entry point for the application
            Overrides Function Run(ByVal channel As UASCallChannel, _
                                   ByVal applicationParameters As String) _
                                   As Integer
    
                Me.Trace.TraceInfo("Start - appParms [{0}]", applicationParameters)
                Dim reply As ReturnCode = ReturnCode.Success
    
                Try
                    Dim callTo = channel.CallDetails.CallTo
                    Me.Trace.TraceInfo("Call started with callTo [{0}]", callTo)
    
                    ' Decode the pincode/username from the callTo
                    Dim tts = GetTtsFromUsername(callTo)
                    channel.Ring(4)
                    channel.Answer()
    
                    ' Say it back to caller
                    channel.FilePlayer.Say( _
                        "Hello, this is the quick start application for {0}. Have a good day. Goodbye.", tts)
    
                Catch ex As Exception
                    Me.Trace.TraceError("Exception thrown {0}", ex.Message)
                    reply = ReturnCode.ExceptionThrown
                Finally
                    channel.HangUp()
                End Try
    
                Me.Trace.TraceInfo("Completed with return code {0}", reply)
                Return reply
    
            End Function
    
            ' Convert the pin code to comma-separated digits.
            Private Function GetTtsFromPinCode(ByVal pinCode As String) As String
                Dim tts = ""
                For Each c In pinCode
                    If tts.Length > 0 Then
                        tts += ", "
                    End If
                    tts += c
                Next
                Return tts
            End Function
    
            ' Get suitable string for TTS based on SIP username in supplied callTo.
            ' The SIP username must start with "sip:".
            ' If next characters are "--" and the remaining 8 digits are numeric then read as a pin code.
            Private Function GetTtsFromUsername(ByVal callTo As String) As String
                ' check we have a sane callTo
                Dim splits = callTo.Split("@")
                If splits.Length <> 2 Then
                    Return "an invalid SIP username"
                End If
    
                If Not splits(0).StartsWith(sipPrefix) Then
                    Return "an invalid SIP username"
                End If
    
                ' Remove the Sip:
                Dim username = splits(0).Substring(sipPrefix.Length)
    
                ' If we have a pin code, try to speak it nicely
                If username.StartsWith(pincodePrefix) Then
                    Dim pinCode = username.Substring(pincodePrefix.Length)
    
                    ' Is it the right length
                    If pinCode.Length <> pinCodeLength Then
                        Return "a pin code that is not of length " + pinCodeLength
                    End If
    
                    Try
                        Dim pinCodeValue = Convert.ToInt32(pinCode)
                    Catch
                        Return "an invalid pin code"
                    End Try
    
                    Me.Trace.TraceInfo("Username [{0}] pincode [{1}]", username, pinCode)
                    Return "user pin code " + GetTtsFromPinCode(pinCode)
                End If
    
                ' Otherwise, just return the username
                Me.Trace.TraceInfo("Username [{0}]", username)
                Return "SIP username " + username
            End Function
        End Class
    
    End Namespace
  • Filename:

    Samples\F#\QuickStart\QuickStart.fs

    Description:

    The application code is initiated via the Run() method that is called by the UAS. Arguments supplied to this method are the UASCallChannel with which SIP and PSTN calls are controlled and an applicationParameters string. This string is specified in the Inbound Service that was invoked and resulted in this application being run.

    The UASCallChannel class contains a property CallDetails which provides information associated with a call. The CallTo property is the destination address of the inbound call. This is manipulated by the GetTtsFromUsername() member function to decode the pincode/username.

    We simulate the phone ringing for four seconds with channel.Ring(4) and then answer the call with channel.Answer(). channel.FilePlayer provides a way of playing wav files and also to convert text into audio speach which can then be played to a call. The Say() method uses Text-To-Speech (TTS) to produce audio data.

    The caller may hangup at any time, in which case the channel.State property will go to Idle. Notice that we can use the Trace property of the application's base class to log application information e.g. obj.Trace.TraceInfo("some log info").

    Code:

    // A simple inbound application that is provided as the default Developer Service Target Entry.
    // It rings the call for 4 seconds, answers the call, then reads out the decoded pin code 
    // and username from the callTo parameter before hanging up.
    namespace QuickStart
    
        open System
        open System.Threading
        open AMSClassLibrary
        open UASAppAPI
    
        // Possible return codes
        type ReturnCode =
            // Success Codes:
            | Success = 0
            // ... any positive integer
    
            // Fail Codes:
            // -1 to -99 reserved
            | ExceptionThrown = -100
    
        // The application class.
        // This must have the same name as the assembly and must inherit from either 
        // UASInboundApplication or UASOutboundApplication.
        // It must override the Run method.
        type QuickStart() = 
            inherit UASInboundApplication()
    
            let sipPrefix = "sip:"
            let pincodePrefix = "--"
            let pinCodeLength = 8
    
            // This is the entry point for the application
            override obj.Run(channel:UASCallChannel, applicationParameters:string) : int = 
                
                let mutable reply = ReturnCode.Success
    
                try
                    try
                        let callTo = channel.CallDetails.CallTo
                        obj.Trace.TraceInfo("Call started with callTo [{0}]", callTo)
    
                        // Decode the pin code/username from the callTo
                        let tts : string = obj.GetTtsFromUsername(callTo)
    
                        channel.Ring(4) |> ignore
                        channel.Answer() |> ignore
    
                        // Say it back to caller
                        channel.FilePlayer.Say("Hello, this is the quick start application for {0}. " + 
                                               "Have a good day. Goodbye.", tts) |> ignore
                    with 
                        | _ as e -> 
                            obj.Trace.TraceError("Exception thrown {0}", e.Message)
                            reply <- ReturnCode.ExceptionThrown
                finally
                    channel.HangUp() |> ignore
    
                obj.Trace.TraceInfo("Completed with return code {0}", reply)
                (int)reply
    
                
            // Convert the pin code to comma-separated digits.
            member obj.GetTtsFromPinCode(pinCode : string) : string =
                ", " + pinCode.Chars(0).ToString() + obj.GetTtsFromPinCode(pinCode.Substring(1))
     
    
            // Get suitable string for TTS based on SIP username in supplied callTo.
            // The SIP username must start with "sip:".
            // If next characters are "--" and the remaining 8 digits are numeric then read as a pin code.
            member obj.GetTtsFromUsername(callTo : string) : string =
                // check we have a sane callTo
                let splits : string [] = callTo.Split('@')
                if splits.Length <> 2 then
                    "an invalid SIP username"
                elif splits.[0].StartsWith(sipPrefix) then
                    "an invalid SIP username"
                else
                    // Remove the Sip:
                    let username : string = splits.[0].Substring(sipPrefix.Length)
                
                    // If we have a pin code, try to speak it nicely
                    if (username.StartsWith(pincodePrefix)) then
                        let pinCode : string = username.Substring(pincodePrefix.Length) 
    
                        // Is it the right length
                        if pinCode.Length <> pinCodeLength then
                            "a pin code that is not of length " + pinCodeLength.ToString()
                        else 
                            try
                                let pinCodeValues = Convert.ToInt32(pinCode)
                                obj.Trace.TraceInfo("Username [{0}] pin code [{1}]", username, pinCode)
                                "user pin code " + obj.GetTtsFromPinCode(pinCode)
                            with
                                | _ as e ->
                                    "an invalid pin code"
                    else
                        // Otherwise, just return the username
                        obj.Trace.TraceInfo("Username [{0}]", username)
                        "SIP username " + username
    

Cloud UAS Sample UAS Connection Test

UAS API - Uas Connection Test Sample Application

  • Filename:

    samples/uas_connection_test.py

    Description:

    This is an inbound application that rings the call for 2 seconds, answers the call, then reads out some text.

    The application grabs the host name and, if application_parameters is not an empty string, it will get that too (application_parameters is configured on the Inbound Services page). The call is then rung and answered using the channel.ring() and channel.answer() functions. A welcome message is played which contains machine's host name and the text from application_parameters.

    Code:

    """
        This is an inbound application that rings the call for 2 seconds, 
        answers the call, then reads out the following text::
    
        "Welcome to your U.A.S application."
        "The voice you are hearing has been commanded by your machine."
        "The hostname of the machine is <hostname>."
        "The application parameter supplied to the application is <application_parameters>. Goodbye."
    
    """
    
    __uas_identify__ = "application"
    __uas_version__ = "1.0b3"
    
    import sys, os, socket
    from prosody.uas import Hangup, Error
    
    def main(channel, application_instance_id, file_man, my_log, application_parameters):
        log_pref = "connection_test"
        call_to = channel.Details.call_to
        my_log.info("{0} started with call_to [{1}]".format(log_pref, call_to))
    
        #grab the machine hostname
        hostname = socket.gethostname()
    
        # Our default text for the application_parameters are "Nothing", which is replaced if there's any text to play
        test_args = "Nothing"
        if application_parameters != "":
            test_args = application_parameters
    
        # The main program
        try:
            # ring for two seconds
            channel.ring(2)
            # answer the call
            channel.answer()
            # say some text. The text is converted to speech using an inbuilt Text-To-Speech (TTS) converter
            channel.FilePlayer.say("Welcome to your U.A.S application. \
                                    The voice you are hearing has been commanded by your machine. \
                                    The hostname of the machine is {0}. \
                                    The application parameters supplied to the application are {1}. Goodbye.".format(hostname, test_args))
            # Hang up the call!
            channel.hang_up()
            
        except Hangup as exc:
            my_log.info("{0} completed with Hangup".format(log_pref))
    
        except Error as exc:
            my_log.error("{0} completed with Error exception! {1}".format(log_pref, exc))
            return -101
    
        except Exception as exc:
            my_log.exception("{0} completed with exception! {1}".format(log_pref, exc))
            return -102
    
        my_log.info("{0} completed".format(log_pref))
        return 0
    
  • Filename:

    Samples\C#\UASConnectionTest\UASConnectionTest.cs

    Description:

    When this application starts, we log the caller and then grab the hostname of the machine from System.Environment.MachineName. We then access the applicationParameters argument, that is specified in the calling inbound service on the Cloud and sent to our application when it is run on our UAS. If there's anything in the parameter list we store it in parametersToSay. Otherwise we set parametersToSay to be "Empty".

    The application simulates the phone ringing with channel.Ring(2), answers the call with channel.Answer() and then uses Text-To-Speech (TTS) to convert some text to voice data. The text to say includes the hostname, gathered from the above code, just to confirm to the user that the UAS is running on their local machine. Additionally, the parametersToSay are played. Finally, the channel is disconnected with channel.HangUp.

    Code:

    using System;
    using System.Threading;
    using AMSClassLibrary;
    using UASAppAPI;
    
    // A simple inbound application that rings the call for 2 seconds, 
    // answers the call, then reads out some text including the machine name on 
    // which the UAS is running and the application parameters sent to the 
    // application, before hanging up.
    //
    // Requires:
    // [applicationParameters = the text to say]
    namespace UASConnectionTest
    {
        public class UASConnectionTest : UASInboundApplication
        {
            public override int Run(UASCallChannel channel,
                                    string applicationParameters)
            {
                string callTo = channel.CallDetails.CallTo;
                this.Trace.TraceInfo("Call started with callTo [{0}]", callTo);
    
                // Grab the machine hostname
                string hostname = System.Environment.MachineName;
    
                // Set what to say if applicationParameters is empty 
                string parametersToSay = "Empty";
                if (applicationParameters.Length > 0)
                {
                    parametersToSay = applicationParameters;
                }
    
                try
                {
                    // Ring for two seconds
                    channel.Ring(2);
    
                    // Answer the call
                    channel.Answer();
            
                    // Say some text. 
                    // The text is converted to speech using the inbuilt Text-To-Speech (TTS) converter
                    channel.FilePlayer.Say("Welcome to your U A S application. " + 
                                           "The voice you are hearing has been commanded by your machine. " +
                                           "The hostname of the machine is {0}.", 
                                           hostname);
                    channel.FilePlayer.Say("The application parameter supplied to the application is {0}.",
                                           parametersToSay);
                    channel.FilePlayer.Say("Goodbye.");
                }
                catch (Exception e)
                {
                    this.Trace.TraceError("Exception thrown {0}", e.Message);
                }
                finally
                {
                    // Hang up the call
                    channel.HangUp();
                }
    
                this.Trace.TraceInfo("Completed");
                return 0;
            }
        }
    }
  • Filename:

    Samples\VB\UASConnectionTest\UASConnectionTest.vb

    Description:

    When this application starts, we log the caller and then grab the hostname of the machine from System.Environment.MachineName. We then access the applicationParameters argument, that is specified in the calling inbound service on the Cloud and sent to our application when it is run on our UAS. If there's anything in the parameter list we store it in parametersToSay. Otherwise we set parametersToSay to be "Empty".

    The application simulates the phone ringing with channel.Ring(2), answers the call with channel.Answer() and then uses Text-To-Speech (TTS) to convert some text to voice data. The text to say includes the hostname, gathered from the above code, just to confirm to the user that the UAS is running on their local machine. Additionally, the parametersToSay are played. Finally, the channel is disconnected with channel.HangUp.

    Code:

    Imports AMSClassLibrary
    Imports UASAppAPI
    
    ' A simple inbound application that rings the call for 2 seconds, 
    ' answers the call, then reads out some text including the machine name on 
    ' which the UAS is running and the application parameters sent to the 
    ' application, before hanging up.
    '
    ' Requires:
    ' [applicationParameters = the text to say]
    Namespace UASConnectionTest
    
        Public Class UASConnectionTest
            Inherits UASInboundApplication
    
            Overrides Function Run(ByVal channel As UASCallChannel, _
                                   ByVal applicationParameters As String) _
                                   As Integer
    
                Dim callTo = channel.CallDetails.CallTo
                Me.Trace.TraceInfo("Call started with callTo [{0}]", callTo)
    
                ' Grab the machine hostname
                Dim hostname = System.Environment.MachineName
    
                ' Set what to say if applicationParameters is empty 
                Dim parametersToSay = "Empty"
                If applicationParameters.Length > 0 Then
                    parametersToSay = applicationParameters
                End If
    
                Try
                    ' Ring for two seconds
                    channel.Ring(2)
    
                    ' Answer the call
                    channel.Answer()
    
                    ' Say some text. 
                    ' The text is converted to speech using the inbuilt Text-To-Speech (TTS) converter
                    channel.FilePlayer.Say("Welcome to your U A S application. " + _
                                           "The voice you are hearing has been commanded by your machine. " + _
                                           "The hostname of the machine is {0}.", _
                                           hostname)
                    channel.FilePlayer.Say("The application parameter supplied to the application is {0}.", _
                                           parametersToSay)
                    channel.FilePlayer.Say("Goodbye.")
                Catch e As Exception
                    Me.Trace.TraceError("Exception thrown {0}", e.Message)
                Finally
                    ' Hang up the call
                    channel.HangUp()
                End Try
    
                Me.Trace.TraceInfo("Completed")
                Return 0
    
            End Function
    
        End Class
    
    End Namespace
  • Filename:

    Samples\F#\UASConnectionTest\UASConnectionTest.fs

    Description:

    When this application starts, we log the caller and then grab the hostname of the machine from System.Environment.MachineName. We then access the applicationParameters argument, that is specified in the calling inbound service on the Cloud and sent to our application when it is run on our UAS. If there's anything in the parameter list we store it in parametersToSay. Otherwise we set parametersToSay to be "Empty".

    The application simulates the phone ringing with channel.Ring(2), answers the call with channel.Answer() and then uses Text-To-Speech (TTS) to convert some text to voice data. The text to say includes the hostname, gathered from the above code, just to confirm to the user that the UAS is running on their local machine. Additionally, the parametersToSay parameter is played. Finally, the channel is disconnected with channel.HangUp and we return 0 to indicate success.

    Code:

    // A simple inbound application that rings the call for 2 seconds, 
    // answers the call, then reads out some text including the machine name on 
    // which the UAS is running and the application parameters sent to the 
    // application, before hanging up.
    //
    // Requires:
    // [applicationParameters = the text to say]
    namespace UASConnectionTest
    
        open AMSClassLibrary
        open UASAppAPI
        open System.Threading
    
        // The application class.
        // This must have the same name as the assembly and must inherit from either 
        // UASInboundApplication or UASOutboundApplication.
        // It must override the Run method.
        type UASConnectionTest() = 
            inherit UASInboundApplication()
    
            // This is the entry point for the application
            override obj.Run(channel:UASCallChannel, applicationParameters:string) : int = 
    
                let callTo = channel.CallDetails.CallTo
                obj.Trace.TraceInfo("Call started with callTo [{0}]", callTo)
    
                // Grab the machine hostname
                let hostname = System.Environment.MachineName
    
                // Set what to say if applicationParameters is empty 
                let parametersToSay = if (applicationParameters.Length > 0) then applicationParameters else "Empty"
    
                try
                    try
                        // Ring for two seconds
                        channel.Ring(2) |> ignore
    
                        // Answer the call
                        channel.Answer() |> ignore
            
                        // Say some text. 
                        // The text is converted to speech using the inbuilt Text-To-Speech (TTS) converter
                        channel.FilePlayer.Say("Welcome to your U A S application. " + 
                                               "The voice you are hearing has been commanded by your machine. " +
                                               "The hostname of the machine is {0}.", 
                                               hostname) |> ignore
                        channel.FilePlayer.Say("The application parameter supplied to the application is {0}.",
                                               parametersToSay) |> ignore
                        channel.FilePlayer.Say("Goodbye.") |> ignore
                    with
                        | _ as e ->
                            obj.Trace.TraceError("Exception thrown {0}", e.Message)
                finally
                    // Hang up the call
                    channel.HangUp() |> ignore
    
                obj.Trace.TraceInfo("Completed")
                0
                
  • Filename:

    Samples\C++\UASConnectionTest\UASConnectionTest.cpp

    Description:

    When this application starts, we log the caller and then grab the hostname of the machine from System::Environment::MachineName. We then access the applicationParameters argument, that is specified in the calling inbound service on the Cloud and sent to our application when it is run on our UAS. If there's anything in the parameter list we store it in parametersToSay. Otherwise we set parametersToSay to be "Empty".

    The application simulates the phone ringing with channel->Ring(2), answers the call with channel->Answer() and then uses Text-To-Speech (TTS) to convert some text to voice data. The text to say includes the hostname, gathered from the above code, just to confirm to the user that the UAS is running on their local machine. Additionally, the parametersToSay are played. Finally, the channel is disconnected with channel->HangUp.

    Code:

    // This is the main DLL file.
    
    #include "stdafx.h"
    #include "UASConnectionTest.h"
    
    // A simple inbound application that rings the call for 2 seconds, 
    // answers the call, then reads out some text including the machine name on 
    // which the UAS is running and the application parameters sent to the 
    // application, before hanging up.
    //
    // Requires:
    // [applicationParameters = the text to say]
    namespace UASConnectionTest 
    {
    	// Possible return codes
    	enum ReturnCode
    	{
    		// Success Codes:
    		Success = 0
    		// ... any positive integer
    
    		// Fail Codes:
    		// -1 to -99 reserved
    	};
    
    	// This is the entry point for the application
    	int UASConnectionTest::Run(UASCallChannel^ channel, String^ applicationParameters)
    	{
    		String^ callTo = channel->CallDetails->CallTo;
    		this->Trace->TraceInfo("Call started with callTo [{0}]", callTo);
    
    		// Grab the machine hostname
    		String^ hostname = System::Environment::MachineName;
    
    		// Set what to say if applicationParameters is empty 
    		String^ parametersToSay = "Empty";
    		if (applicationParameters->Length > 0)
    		{
    			parametersToSay = applicationParameters;
    		}
    
    		try
    		{
    			// Ring for two seconds
    			channel->Ring(2);
    
    			// Answer the call
    			array<String^>^ emptyCodecs = gcnew array<String^>(0);
    			channel->Answer(emptyCodecs);
    
    			// Say some text. 
    			// The text is converted to speech using the inbuilt Text-To-Speech (TTS) converter
    			channel->FilePlayer->Say("Welcome to your U A S application. " + 
    									 "The voice you are hearing has been commanded by your machine. " +
    									 "The hostname of the machine is {0}.", 
    									 hostname);
    			channel->FilePlayer->Say("The application parameter supplied to the application is {0}.",
    									 parametersToSay);
    			channel->FilePlayer->Say("Goodbye.");
    		}
    		catch (Exception^ e)
    		{
    			this->Trace->TraceError("Exception thrown {0}", e->Message);
    		}
    		finally
    		{
    			// Hang up the call
    			channel->HangUp();
    		}
    
    		this->Trace->TraceInfo("Completed");
    
    		return Success;
    	};
    }
    

Cloud UAS Sample Inbound With TTS

UAS API - Inbound With Tts Sample Application

  • Filename:

    samples/inbound_with_tts.py

    Description:

    An application that answers an inbound call and speaks some TTS. After ringing and answering the channel, the channel.FilePlayer.say() function is used to speak the text by converting the given text string into voice data. The process is known as Text-To-Speech (TTS).

    The text to be spoken is passed to the application via the application_parameters variable which is configured on the Inbound Services page (Manage -> Inbound Services). The say function will block until the text has been spoken, and then the call will hang up.

    Code:

    # -*- coding: utf-8 -*-
    """
    A simple application that answers an inbound call and speaks some TTS.
    The TTS to say is passed in through application_parameters, which is
    configured on the inbound services page of the CWP. In addition, this
    sample will speak the current date and time.
    
        Actions:
            - check the channel state
            - ring and answer
            - play some tts - provided in application_parameters
            - say the date and time
            - hang up
    
    """
    
    from prosody.uas import Hangup, Error
    import time
    
    __uas_version__  = "0.0.1"
    __uas_identify__ = "application"
    
    def main(channel, application_instance_id, file_man, my_log, application_parameters):
        return_code = 0
        try:
            # check the incoming channel state
            state = channel.state()
            if state == channel.State.CALL_INCOMING:
                state = channel.ring()   # this can raise a Hangup exception
                if state == channel.State.RING_INCOMING:
                    state = channel.answer() # this can raise a Hangup exception
            else:
                raise Hangup('No inbound call, state is {0}'.format(state))
            if state != channel.State.ANSWERED:
                raise Hangup('Failed to answer inbound call, state is {0}'.format(state))
            
            my_log.info("Answered an inbound call") # log at info level
    
            # Say a TTS prompt, the text is provided in application_parameters.
            # This will use the default TTS engine and voice.
            # Note that if your application_parameters contains Unicode characters, 
            # you may need to call an appropriate encode function here
            cause = channel.FilePlayer.say(application_parameters)
            if cause != channel.FilePlayer.Cause.NORMAL:
                raise Error("Say hello failed: cause is {0}".format(cause))
    
            # Now say the date and the time.
            # You can use SSML tags to select a different TTS engine and voice. 
            # The engines and voices available may depend on your account settings.
            # SSML is also used to change the way the text is spoken. 
            # See the online documentation for more information on SSML.
            # Here we use SSML tags to specify some text as a date and time.
            
            # Create a date string in the format year-month-day.
            date = time.strftime("%Y/%m/%d", time.localtime(time.time()))
            
            # Inform the TTS engine that the string should be spoken as a date.
            cause = channel.FilePlayer.say("The date is <say-as interpret-as='date' format='ymd'>{0}</say-as>".format(date))
    
            # Create a time string in the format hours-minutes-seconds
            timestr = time.strftime("%H:%M:%S", time.localtime(time.time()))
    
            # Inform the TTS engine that the string should be spoken as a time.
            cause = channel.FilePlayer.say("The time is <say-as interpret-as='time' format='hms24'>{0}</say-as>".format(timestr))
    
            if cause != channel.FilePlayer.Cause.NORMAL:
                raise Error("TTS player returned {0}: expected {1}".format(cause, channel.FilePlayer.Cause.NORMAL))
            
            # Bye bye, using the default settings.
            cause = channel.FilePlayer.say("Bye bye.")
            if cause != channel.FilePlayer.Cause.NORMAL:
                raise Error("Say bye bye failed: cause is {0}".format(cause))
            
        except Hangup as exc:
            my_log.info("Hangup exception reports: {0}".format(exc))
             # in this app a hangup is not an error, return a positive value
            return_code = 100
            
        except Error as exc:
            # for error conditions return a negative value
            my_log.error("Error exception reports: {0}".format(exc))
            return_code = -101
            
        except Exception as exc:
            # an unexpected exception, return a negative value
            my_log.exception("Unexpected exception reports: {0}".format(exc))
            return_code = -102
            
        finally:
            if channel.state() != channel.State.IDLE:
                channel.hang_up()
    
        return return_code
    
  • Filename:

    Samples\C#\InboundWithTTS\InboundWithTTS.cs

    Description:

    First we ring and answer the call. Then we check the applicationParameters for some text with which to generate audio on the call. The applicationParameters argument is passed to our application by the UAS which receives it from the cloud. This argument is set in the Modify Existing Inbound Service page for the service that invoked our application.

    After text manipulation, we say the text using channel.FilePlayer.Say(), which converts the given text into audio using Text-To-Speech (TTS). Finally, we hang up the call using channel.HangUp().

    Code:

    using System;
    using AMSClassLibrary;
    using UASAppAPI;
    
    // An inbound application that says some text (passed in) to the
    // caller followed by the current date and time then hangs up.
    //
    // Requires:
    // [applicationParameters = the text to say]
    namespace InboundWithTTS
    {
        // The application class.
        // This must have the same name as the assembly and must inherit from either 
        // UASInboundApplication or UASOutboundApplication.
        // It must override the Run method.
        public class InboundWithTTS : UASInboundApplication
        {
            enum ReturnCode
            {
                // Success Codes:
                Success = 0,
                // ... any positive integer
    
                // Fail Codes:
                // -1 to -99 reserved
                ExceptionThrown = -100,
                PlayInterrupted = -101
            }
    
            // This is the entry point for the application
            public override int Run(UASCallChannel channel, string applicationParameters)
            {
                this.Trace.TraceInfo("Start - appParms [{0}]", applicationParameters);
                ReturnCode reply = ReturnCode.Success;
    
                try
                {
                    // Ring for 2 seconds
                    channel.Ring(2);
    
                    // Answer the call
                    CallState state = channel.Answer();
                    if (state == CallState.Answered)
                    {
                        this.Trace.TraceInfo("Answered");
    
                        if (applicationParameters.Length == 0)
                        {
                            applicationParameters = "no text was provided to say.";
                        }
                        
                        // Say the current date and the time 
                        // in the default TTS engine and voice.
    
                        // This uses SSML tags to determine the way the text is spoken. 
                        // See /documents/tts on your platform for more information on SSML.
                        DateTime now = DateTime.Now.ToLocalTime();
    
                        // Create TTS date text with SSML tags that specify how the date should be spoken.
                        string ttsDate = String.Format(
                            "<say-as interpret-as='date' format='dmy'>{0:dd/MM/yyyy}</say-as>",
                            now);
    
                        // Create TTS time text with SSML tags that specify how the time should be spoken.
                        string ttsTime = String.Format(
                            "<say-as interpret-as='time' format='hms24'>{0:HH:mm:ss}</say-as>",
                            now);
    
                        // Say the date 
                        FilePlayerCause playCause = channel.FilePlayer.Say(
                            "The current date is {0} and the time is {1}",
                                ttsDate,
                                ttsTime);
                        if (FilePlayerCause.Normal != playCause)
                        {
                            this.Trace.TraceError("Say failed or was interrupted");
                            reply = ReturnCode.PlayInterrupted;
                        }
                        else
                        {
                            // Now say the text provided in the application Parameters 
                            // field of the calling service using TTS.
                            playCause = channel.FilePlayer.Say(applicationParameters);
                            if (FilePlayerCause.Normal != playCause)
                            {
                                this.Trace.TraceError("Say failed or was interrupted");
                                reply = ReturnCode.PlayInterrupted;
                            }
                            else
                            {
                                // Say Goodbye using the default voice
                                channel.FilePlayer.Say("Goodbye.");
                            }
                        }
    
                        // Ensure the call is hung up.
                        channel.HangUp();
                    }
                }
                catch (Exception e)
                {
                    this.Trace.TraceError("Exception caught: {0}", e.Message);
                    reply = ReturnCode.ExceptionThrown;
                }
    
                this.Trace.TraceInfo("Completed with return code {0}", reply);
                return (int)reply;
            }
        }
    }
    
  • Filename:

    Samples\VB\InboundWithTTS\InboundWithTTS.vb

    Description:

    First we ring and answer the call. Then we check the applicationParameters for some text with which to generate audio on the call. The applicationParameters argument is passed to our application by the UAS which receives it from the cloud. This argument is set in the Modify Existing Inbound Service page for the service that invoked our application.

    After text manipulation, we say the text using channel.FilePlayer.Say(), which converts the given text into audio using Text-To-Speech (TTS). Finally, we hang up the call using channel.HangUp().

    Code:

    Imports AMSClassLibrary
    Imports UASAppAPI
    
    ' An inbound application that says some text (passed in) to the
    ' caller followed by the current date and time then hangs up.
    '
    ' Requires:
    ' [applicationParameters = the text to say]
    Namespace InboundWithTTS
    
        ' The application class.
        ' This must have the same name as the assembly and must inherit from either 
        ' UASInboundApplication or UASOutboundApplication.
        ' It must override the Run method.
        Public Class InboundWithTTS
            Inherits UASInboundApplication
    
            ' Possible return codes
            Enum ReturnCode
                ' Success Codes:
                Success = 0
                ' ... any positive integer
    
                ' Fail Codes:
                ' -1 to -99 reserved
                ExceptionThrown = -100
                PlayInterrupted = -101
            End Enum
    
            ' This is the entry point for the application
            Overrides Function Run(ByVal channel As UASCallChannel, _
                                   ByVal applicationParameters As String) _
                                   As Integer
    
                Me.Trace.TraceInfo("Start - appParms [{0}]", applicationParameters)
                Dim reply As ReturnCode = ReturnCode.Success
    
                Try
                    ' Ring for 2 seconds
                    channel.Ring(2)
    
                    ' Answer the call
                    Dim state As CallState
                    state = channel.Answer()
    
                    If state = CallState.Answered Then
    
                        Me.Trace.TraceInfo("Call answered")
    
                        If String.IsNullOrEmpty(applicationParameters) Then
                            applicationParameters = "No text was provided to play"
                        End If
    
                        ' Say the current date and the time 
                        ' in the default TTS engine and voice.
    
                        ' This uses SSML tags to determine the way the text is spoken. 
                        ' See /documents/tts on your platform for more information on SSML.
    
                        ' Create TTS date text with SSML tags that specify how the date should be spoken.
                        Dim now = DateTime.Now.ToLocalTime()
                        Dim ttsDate = String.Format( _
                            "<say-as interpret-as='date' format='dmy'>{0:dd/MM/yyyy}</say-as>", _
                            now)
    
                        ' Create TTS time text with SSML tags that specify how the time should be spoken.
                        Dim ttsTime = String.Format( _
                            "<say-as interpret-as='time' format='hms24'>{0:HH:mm:ss}</say-as>", _
                            now)
    
                        ' Say the date 
                        Dim playCause = channel.FilePlayer.Say( _
                            "The current date is {0} and the time is {1}", _
                                ttsDate, _
                                ttsTime)
                        If FilePlayerCause.Normal <> playCause Then
                            Me.Trace.TraceError("Say failed or was interrupted")
                            reply = ReturnCode.PlayInterrupted
                        Else
                            ' Now say the text provided in the application Parameters 
                            ' field of the calling service using TTS.
                            playCause = channel.FilePlayer.Say(applicationParameters)
                            If FilePlayerCause.Normal <> playCause Then
                                Me.Trace.TraceError("Say failed or was interrupted")
                                reply = ReturnCode.PlayInterrupted
                            Else
                                ' Say Goodbye using the default voice
                                channel.FilePlayer.Say("Goodbye.")
                            End If
                        End If
    
                        ' Ensure the call is hung up.
                        channel.HangUp()
                    End If
    
                Catch ex As Exception
                    Me.Trace.TraceError("Exception thrown {0}", ex.Message)
                    reply = ReturnCode.ExceptionThrown
                End Try
    
                Me.Trace.TraceInfo("Completed with return code {0}", reply)
                Return reply
    
            End Function
    
        End Class
    
    End Namespace
  • Filename:

    Samples\F#\InboundWithTTS\InboundWithTTS.fs

    Description:

    First we ring and answer the call. Then we check the applicationParameters for some text with which to generate audio on the call. The applicationParameters argument is passed to our application by the UAS which receives it from the cloud. This argument is set in the Modify Existing Inbound Service page for the service that invoked our application.

    After text manipulation, we say the text using channel.FilePlayer.Say(), which converts the given text into audio using Text-To-Speech (TTS). Finally, we hang up the call using channel.HangUp().

    Code:

    // An inbound application that says some text (passed in) to the
    // caller then hangs up.
    //
    // Requires:
    // [applicationParameters = the text to say]
    namespace InboundWithTTS
    
        open System
        open System.Threading
        open AMSClassLibrary
        open UASAppAPI
    
        // Possible return codes
        type ReturnCode =
            // Success Codes:
            | Success = 0
            // ... any positive integer
    
            // Fail Codes:
            // -1 to -99 reserved
            | ExceptionThrown = -100
            | PlayInterrupted = -101
    
        // The application class.
        // This must have the same name as the assembly and must inherit from either 
        // UASInboundApplication or UASOutboundApplication.
        // It must override the Run method.
        type InboundWithTTS() = 
            inherit UASInboundApplication()
    
            // This is the entry point for the application
            override obj.Run(channel:UASCallChannel, applicationParameters:string) : int = 
                
                obj.Trace.TraceInfo("In - appParms [{0}]", applicationParameters)
                let mutable reply = ReturnCode.Success
    
                try
                    // Ring for 2 seconds
                    channel.Ring(2) |> ignore
    
                    // Answer the call
                    if channel.Answer() = CallState.Answered then
    
                        obj.Trace.TraceInfo("Call answered")
    
                        if applicationParameters.Length = 0 then
                            channel.FilePlayer.Say("no text was provided to say.") |> ignore
                        elif channel.FilePlayer.Say(applicationParameters) <> FilePlayerCause.Normal then
                            obj.Trace.TraceError("Play failed or was interrupted")
                            reply <- ReturnCode.PlayInterrupted
    
                        channel.HangUp() |> ignore
                with 
                    | _ as e -> 
                        obj.Trace.TraceError("Exception caught {0}", e.Message)
                        reply <- ReturnCode.ExceptionThrown
    
                    
                obj.Trace.TraceInfo("Completed")
                (int)reply
                

Cloud UAS Sample Inbound With Speech

UAS API - Inbound With Speech Sample Application

  • Filename:

    samples/inbound_with_speech.py

    Description:

    An inbound application that prompts the caller to say a number between sixteen and ninety nine. After ringing and answering an inbound call, the application primes the speech recogniser to start recognising speech after the next play has ended. It selects a predefined grammar, SixteenToNinetyNine, for the recognition job. The application then uses TTS to ask for the caller's age, which should be between sixteen and ninety nine.

    The caller can respond by pressing digits instead of speaking. If this happens, the application will collect the DTMF digits that were pressed. Finally, the application will speak back to the caller what was said, or pressed, using TTS.

    Code:

    # -*- coding: utf-8 -*-
    """
    A simple application that answers an inbound call, speaks some TTS, 
    detects some speech and plays back the speech that was detected.
    
        Actions:
            - check the channel state
            - ring and answer
            - play some tts
            - detect a spoken response
            - play what was detected
            - hang up
    
    The speech detection grammar used is pre-defined.
    
    """
    
    from prosody.uas import Hangup, Error
    import time
    
    __uas_version__  = "0.0.1"
    __uas_identify__ = "application"
    
    def main(channel, application_instance_id, file_man, my_log, application_parameters):
        return_code = 0
        try:
            # check the incoming channel state
            state = channel.state()
    
            if state == channel.State.CALL_INCOMING:
                state = channel.ring()   # this can raise a Hangup exception
                if state == channel.State.RING_INCOMING:
                    state = channel.answer() # this can raise a Hangup exception
            else:
                raise Hangup('No inbound call, state is {0}'.format(state))
            if state != channel.State.ANSWERED:
                raise Hangup('Failed to answer inbound call, state is {0}'.format(state))
            
            my_log.info("Answered an inbound call") # log at info level
    
            channel.FileRecorder.start("speech_test_{0}.wav".format(application_instance_id))
            # prepare the speech detector, speech detection will begin as soon
            # as the prompt has finished playing
            my_grammar = channel.SpeechDetector.Grammar()
            my_grammar.create_from_predefined('SixteenToNinetyNine')
            if channel.SpeechDetector.prime(my_grammar, channel.SpeechDetector.SpeechDetectorTrigger.ONPLAYEND) is False:
                raise Error("Speech detector failed to start")
    
            # Say the TTS prompt, the text will ask the caller their age, a value from sixteen to ninety nine.
            cause = channel.FilePlayer.say("<acu-engine name='Polly'><voice name='Amy'>How old are you?</voice></acu-engine>")
            if cause != channel.FilePlayer.Cause.NORMAL:
                raise Error("Say prompt failed: cause is {0}".format(cause))
    
            # Now get the recognised speech, can be words or DTMF digits
            response = channel.SpeechDetector.get_recognised_speech()
            if channel.SpeechDetector.cause() == channel.SpeechDetector.Cause.BARGEIN:
                # age is 16 to 99, so we want two digits
                age = channel.DTMFDetector.get_digits(count=2)
            else:
                age = response.get_recognised_words_as_string()
            if not age:
                to_say = "Sorry, I did not hear that."
            else:
                to_say = "Your age is {0}.".format(age)
            # Say the recognised speech.
            cause = channel.FilePlayer.say("<acu-engine name='Polly'><voice name='Amy'>{0}</voice></acu-engine>".format(to_say))
    
            if cause != channel.FilePlayer.Cause.NORMAL:
                raise Error("TTS player returned {0}: expected {1}".format(cause, channel.FilePlayer.Cause.NORMAL))
            
            # Bye bye.
            cause = channel.FilePlayer.say("Bye bye.")
            if cause != channel.FilePlayer.Cause.NORMAL:
                raise Error("Say bye bye failed: cause is {0}".format(cause))
            
        except Hangup as exc:
            my_log.info("Hangup exception reports: {0}".format(exc))
             # in this app a hangup is not an error, return a positive value
            return_code = -100
            
        except Error as exc:
            # for error conditions return a negative value
            my_log.error("Error exception reports: {0}".format(exc))
            return_code = -101
            
        except Exception as exc:
            # an unexpected exception, return a negative value
            my_log.exception("Unexpected exception reports: {0}".format(exc))
            return_code = -102
            
        finally:
            channel.FileRecorder.stop()
            if channel.state() != channel.State.IDLE:
                channel.hang_up()
    
        return return_code
    
  • Filename:

    Samples\C#\InboundWithSpeech\InboundWithSpeech.cs

    Description:

    First we ring and answer the call. Then we create a Grammar object that will determine the words that the SpeechDetector on the call will try to recognise. This is passed to the Prime method which readies the SpeechDetector to start recognising speech input after the next play has ended. We give the SpeechDetector 10 seconds to recognise some speech input.

    Having primed the SpeechDetector we play a prompt to the caller and then wait for any speech input to be recognised. If the Cause is Normal we have a valid recognised result and play back the recognised word to the call.

    Note: if the SpeechDetector didn't recognise one of the expected words or was interrupted by a press on the caller's telephone keypad we could then also use the DTMFDetector to identify the keys pressed. This would provide an alternative means of number input if the caller's environment is too loud or disturbed for accurate recognition.

    Code:

    using System;
    using AMSClassLibrary;
    using UASAppAPI;
    
    // An inbound application that prompts the caller to say some text 
    // then reads the recognised text back to the caller and hangs up.
    //
    // Requires:
    // -
    namespace InboundWithSpeech
    {
        // The application class.
        // This must have the same name as the assembly and must inherit from either 
        // UASInboundApplication or UASOutboundApplication.
        // It must override the Run method.
        public class InboundWithSpeech : UASInboundApplication
        {
            enum ReturnCode
            {
                // Success Codes:
                Success = 0,
                // ... any positive integer
    
                // Fail Codes:
                // -1 to -99 reserved
                ExceptionThrown = -100,
                PlayInterrupted = -101,
                NoResponse = -102
            }
    
            // This is the entry point for the application
            public override int Run(UASCallChannel channel, string applicationParameters)
            {
                this.Trace.TraceInfo("Start - appParms [{0}]", applicationParameters);
                ReturnCode reply = ReturnCode.Success;
    
                try
                {
                    // Ring for 2 seconds
                    channel.Ring(2);
    
                    // Answer the call
                    CallState state = channel.Answer();
                    if (state == CallState.Answered)
                    {
                        this.Trace.TraceInfo("Answered");
    
                        // Prime the speech recognition to listen when the prompt has finished playing
                        Grammar listenFor = Grammar.CreateFromAlternatives(new String[] { "apricots", "apples", "pears", "pomegranates" });
                        if (!channel.SpeechDetector.Prime(SpeechDetectorTrigger.OnPlayEnd, listenFor, 10))
                        {
                            this.Trace.TraceError("Failed to prime speech recognition");
                            reply = ReturnCode.PlayInterrupted;
                        }
    
                        // Prompt the caller to make a selection by saying one of the following
                        FilePlayerCause playCause = channel.FilePlayer.Say(
                            "Hello. You've reached the Inbound With Speech sample. Please say one of the following: apricots, apples, pears, pomegranates");
                        if (FilePlayerCause.Normal != playCause)
                        {
                           this.Trace.TraceError("Say failed or was interrupted");
                            reply = ReturnCode.PlayInterrupted;
                        }
                        else
                        {
                            // Now wait for speech recognition
                            SpeechDetectorResult result;
                            SpeechDetectorCause speechCause = channel.SpeechDetector.GetRecognisedSpeech(out result);
                            if (speechCause == SpeechDetectorCause.Normal)
                            {
                                this.Trace.TraceInfo("Got speech result: {0}", result.ToString());
    
                                // Now say the recognised text using TTS.
                                playCause = channel.FilePlayer.Say(String.Join(" ", result.RecognisedWords.ToArray()));
                                if (FilePlayerCause.Normal != playCause)
                                {
                                    this.Trace.TraceError("Say failed or was interrupted");
                                    reply = ReturnCode.PlayInterrupted;
                                }
                            }
                            else
                            {
                                this.Trace.TraceInfo("GetRecognisedSpeech returned {0}", speechCause.ToString());
                                this.Trace.TraceError("No response was recognised");
                                reply = ReturnCode.NoResponse;
                            }
                        }
    
                        // Say Goodbye using the default voice
                        channel.FilePlayer.Say("Goodbye.");
    
                        // Ensure the call is hung up.
                        channel.HangUp();
                    }
                }
                catch (Exception e)
                {
                    this.Trace.TraceError("Exception caught: {0}", e.Message);
                    reply = ReturnCode.ExceptionThrown;
                }
    
                this.Trace.TraceInfo("Completed with return code {0}", reply);
                return (int)reply;
            }
        }
    }
    
  • Filename:

    Samples\VB\InboundWithSpeech\InboundWithSpeech.vb

    Description:

    First we ring and answer the call. Then we create a Grammar object that will determine the words that the SpeechDetector on the call will try to recognise. This is passed to the Prime method which readies the SpeechDetector to start recognising speech input after the next play has ended. We give the SpeechDetector 10 seconds to recognise some speech input.

    Having primed the SpeechDetector we play a prompt to the caller and then wait for any speech input to be recognised. If the Cause is Normal we have a valid recognised result and play back the recognised word to the call.

    Note: if the SpeechDetector didn't recognise one of the expected words or was interrupted by a press on the caller's telephone keypad we could then also use the DTMFDetector to identify the keys pressed. This would provide an alternative means of number input if the caller's environment is too loud or disturbed for accurate recognition.

    Code:

    Imports AMSClassLibrary
    Imports UASAppAPI
    
    ' An inbound application that prompts the caller to say some text 
    ' then reads the recognised text back to the caller And hangs up.
    '
    ' Requires:
    ' -
    Namespace InboundWithSpeech
    
        ' The application class.
        ' This must have the same name as the assembly and must inherit from either 
        ' UASInboundApplication or UASOutboundApplication.
        ' It must override the Run method.
        Public Class InboundWithSpeech
            Inherits UASInboundApplication
    
            ' Possible return codes
            Enum ReturnCode
                ' Success Codes:
                Success = 0
                ' ... any positive integer
    
                ' Fail Codes:
                ' -1 to -99 reserved
                ExceptionThrown = -100
                PlayInterrupted = -101
                NoResponse = -102
            End Enum
    
            ' This is the entry point for the application
            Overrides Function Run(ByVal channel As UASCallChannel,
                                   ByVal applicationParameters As String) _
                                   As Integer
    
                Me.Trace.TraceInfo("Start - appParms [{0}]", applicationParameters)
                Dim reply As ReturnCode = ReturnCode.Success
    
                Try
                    ' Ring for 2 seconds
                    channel.Ring(2)
    
                    ' Answer the call
                    Dim state As CallState
                    state = channel.Answer()
    
                    If state = CallState.Answered Then
    
                        Me.Trace.TraceInfo("Call answered")
    
                        ' Prime the speech recognition to listen when the prompt has finished playing
                        Dim options As String() = {"apricots", "apples", "pears", "pomegranates"}
                        Dim listenFor As Grammar = Grammar.CreateFromAlternatives(options)
                        If Not channel.SpeechDetector.Prime(SpeechDetectorTrigger.OnPlayEnd, listenFor, 10) Then
                            Me.Trace.TraceError("Failed to prime speech recognition")
                            reply = ReturnCode.PlayInterrupted
                        End If
    
                        ' Prompt the caller to make a selection by saying one of the following
                        Dim playCause As FilePlayerCause = channel.FilePlayer.Say(
                            "Hello. You've reached the Inbound With Speech sample. Please say one of the following: " _
                            + String.Join(", ", options))
                        If FilePlayerCause.Normal <> playCause Then
                            Me.Trace.TraceError("Say failed or was interrupted")
                            reply = ReturnCode.PlayInterrupted
                        Else
                            ' Now wait for speech recognition
                            Dim result As SpeechDetectorResult = Nothing
                            Dim speechCause As SpeechDetectorCause = channel.SpeechDetector.GetRecognisedSpeech(result)
                            If speechCause = SpeechDetectorCause.Normal Then
                                Me.Trace.TraceInfo("Got speech result: {0}", result.ToString())
    
                                ' Now say the recognised text using TTS.
                                playCause = channel.FilePlayer.Say(String.Join(" ", result.RecognisedWords.ToArray()))
                                If FilePlayerCause.Normal <> playCause Then
                                    Me.Trace.TraceError("Say failed or was interrupted")
                                    reply = ReturnCode.PlayInterrupted
                                End If
                            Else
                                Me.Trace.TraceInfo("GetRecognisedSpeech returned {0}", speechCause.ToString())
                                Me.Trace.TraceError("No response was recognised")
                                reply = ReturnCode.NoResponse
                            End If
                        End If
    
                        ' Say Goodbye using the default voice
                        channel.FilePlayer.Say("Goodbye.")
    
                        ' Ensure the call is hung up.
                        channel.HangUp()
                    End If
    
                Catch ex As Exception
                    Me.Trace.TraceError("Exception thrown {0}", ex.Message)
                    reply = ReturnCode.ExceptionThrown
                End Try
    
                Me.Trace.TraceInfo("Completed with return code {0}", reply)
                Return reply
    
            End Function
    
        End Class
    
    End Namespace

Cloud UAS Sample Inbound Play Wav

UAS API - Inbound Play Wav Sample Application

  • Filename:

    samples/inbound_play_wav.py

    Description:

    This sample will answer an inbound call and play a wav file. It requires that the wav file to play has been uploaded to the cloud, this can be done on the Media File Management page (Manage -> Media Files). The name of the wav file is passed to the application via the application_parameters variable which is configured on the Inbound Services page (Manage -> Inbound Services).

    After ringing and answering the call, the channel.FilePlayer.play() function is used to play the wav file. The name of the wav file is taken from application_parameters. This will halt our application until the wave. This function will block until the file has finished playing - it is possible to start playing a file and then continue with the application by using the channel.FilePlayer.start() function instead.

    Code:

    """
    A simple example that will answer an inbound call and play a wav file.
    The wav to play is passed in through application_parameters, which is
    configured on the inbound services page of the CWP.
    
        Actions:
            - check the channel state
            - ring and answer
            - play a file - file name in application_parameters
            - hang up
    
    """
    
    from prosody.uas import Hangup, Error, AESCBCCipher
    import time
    
    __uas_version__  = "0.0.1"
    __uas_identify__ = "application"
    
    def main(channel, application_instance_id, file_man, my_log, application_parameters):
        return_code = 0
        try:
            # This application will play a file. If the file is encrypted it must
            # be validated before it can be played. Validation should happen before
            # the call is answered.
            # In the bit of code below we assume that the cipher key and vector are supplied 
            # in application_parameters, along with the file name (using ; as the delimiter).
    
            # check the incoming channel state
            state = channel.state()
            if state == channel.State.CALL_INCOMING:
                state = channel.ring()   # this can raise a Hangup exception
                if state == channel.State.RING_INCOMING:
                    state = channel.answer() # this can raise a Hangup exception
            else:
                raise Hangup('No inbound call, state is {0}'.format(state))
            if state != channel.State.ANSWERED:
                raise Hangup('Failed to answer inbound call, state is {0}'.format(state))
            
            my_log.info("Answered an inbound call") # log at info level
    
            # play a wav file, file name is provided in application_parameters
            cause = channel.FilePlayer.play(application_parameters)
            if cause != channel.FilePlayer.Cause.NORMAL:
                raise Error("Play failed: cause is {0}".format(cause))
    
            # Bye bye
            cause = channel.FilePlayer.say("Bye bye.")
            if cause != channel.FilePlayer.Cause.NORMAL:
                raise Error("Say bye bye failed: cause is {0}".format(cause))
            
        except Hangup as exc:
            my_log.info("Hangup exception reports: {0}".format(exc))
             # in this app a hangup is not an error, return a positive value
            return_code = 100
            
        except Error as exc:
            # for error conditions return a negative value
            my_log.error("Error exception reports: {0}".format(exc))
            return_code = -101
            
        except Exception as exc:
            # an unexpected exception, return a negative value
            my_log.exception("Unexpected exception reports: {0}".format(exc))
            return_code = -102
            
        finally:
            if channel.state() != channel.State.IDLE:
                channel.hang_up()
    
        return return_code
    
    
  • Filename:

    Samples\C#\InboundPlayWav\InboundPlayWav.cs

    Description:

    For this example, you will need to upload a wav file (e.g. via the Media Files menu option). Once uploaded, note the pathname and filename. To run this application, insert the filename into the Application Parameters field of the Inbound Service that runs this application.

    We call Ring and Answer and then play the file using channel.FilePlayer.Play(). This plays the wav file contained in the applicationParameters argument, blocking until the wav file has finished playing. Note that we could have started played the file without blocking using the channel.FilePlayer.Start() method.

    Code:

    using System;
    using System.Threading;
    using AMSClassLibrary;
    using UASAppAPI;
    
    // An inbound application that plays a wav file to the
    // caller then hangs up.
    //
    // Requires:
    // [applicationParameters = the wav filename]
    namespace InboundPlayWav
    {
        // The application class.
        // This must have the same name as the assembly and must inherit from either 
        // UASInboundApplication or UASOutboundApplication.
        // It must override the Run method.
        public class InboundPlayWav : UASInboundApplication
        {
            enum ReturnCode
            {
                // Success Codes:
                Success = 0,
                // ... any positive integer
    
                // Fail Codes:
                // -1 to -99 reserved
                ExceptionThrown = -100,
                PlayInterrupted = -101
            }
    
            // This is the entry point for the application
            public override int Run(UASCallChannel channel, string applicationParameters)
            {
                this.Trace.TraceInfo("Start - appParms [{0}]", applicationParameters);
                ReturnCode reply = ReturnCode.Success;
    
                try
                {
                    // Ring for 2 seconds
                    channel.Ring(2);
    
                    // Answer the call
                    CallState state = channel.Answer();
                    if (state == CallState.Answered)
                    {
                        this.Trace.TraceInfo("Answered");
    
                        if (applicationParameters.Length == 0)
                        {
                            channel.FilePlayer.Say("No wav file name was specified to play");
                        }
                        else
                        {
                            FilePlayerCause playCause = channel.FilePlayer.Play(applicationParameters);
                            if (FilePlayerCause.Normal != playCause)
                            {
                                this.Trace.TraceError("Play failed or was interrupted");
                                reply = ReturnCode.PlayInterrupted;
                            }
                        }
    
                        channel.HangUp();
                    }
                }
                catch (Exception e)
                {
                    this.Trace.TraceError("Exception caught: {0}", e.Message);
                    reply = ReturnCode.ExceptionThrown;
                }
    
                this.Trace.TraceInfo("Completed");
                return (int)reply;
            }
        }
    }
    
  • Filename:

    Samples\VB\InboundPlayWav\InboundPlayWav.vb

    Description:

    For this example, you will need to upload a wav file (e.g. via the Media Files menu option). Once uploaded, note the pathname and filename. To run this application, insert the filename into the Application Parameters field of the Inbound Service that runs this application.

    We call Ring and Answer and then play the file using channel.FilePlayer.Play(). This plays the wav file contained in the applicationParameters argument, blocking until the wav file has finished playing. Note that we could have started played the file without blocking using the channel.FilePlayer.Start() method.

    Code:

    Imports AMSClassLibrary
    Imports UASAppAPI
    
    ' An inbound application that plays a wav file (filename passed in) to the
    ' caller then hangs up.
    '
    ' Requires:
    ' [applicationParameters = the wav filename]
    Namespace InboundPlayWav
    
        ' The application class.
        ' This must have the same name as the assembly and must inherit from either 
        ' UASInboundApplication or UASOutboundApplication.
        ' It must override the Run method.
        Public Class InboundPlayWav
            Inherits UASInboundApplication
    
            ' Possible return codes
            Enum ReturnCode
                ' Success Codes:
                Success = 0
                ' ... any positive integer
    
                ' Fail Codes:
                ' -1 to -99 reserved
                ExceptionThrown = -100
                PlayInterrupted = -101
            End Enum
    
            ' This is the entry point for the application
            Overrides Function Run(ByVal channel As UASCallChannel, _
                                   ByVal applicationParameters As String) _
                                   As Integer
    
                Me.Trace.TraceInfo("In - appParms [{0}]", applicationParameters)
                Dim reply As ReturnCode = ReturnCode.Success
    
                Try
                    ' Ring for 2 seconds
                    channel.Ring(2)
    
                    ' Answer the call
                    Dim state As CallState
                    state = channel.Answer()
                    If state = CallState.Answered Then
    
                        Me.Trace.TraceInfo("Answered")
    
                        If String.IsNullOrEmpty(applicationParameters) Then
                            channel.FilePlayer.Say("No wav file name was specified to play")
                        Else
                            ' Play the specified file
                            Dim playCause = channel.FilePlayer.Play(applicationParameters)
                            If FilePlayerCause.Normal <> playCause Then
                                Me.Trace.TraceError("Play failed or was interrupted")
                                reply = ReturnCode.PlayInterrupted
                            End If
                        End If
    
                        channel.HangUp()
                    End If
    
                Catch ex As Exception
                    Me.Trace.TraceError("Exception thrown {0}", ex.Message)
                    reply = ReturnCode.ExceptionThrown
                End Try
    
                Me.Trace.TraceInfo("Completed")
                Return reply
    
            End Function
    
        End Class
    
    End Namespace
  • Filename:

    Samples\F#\InboundPlayWav\InboundPlayWav.fs

    Description:

    For this example, you will need to upload a wav file (e.g. via the Media Files menu option). Once uploaded, note the pathname and filename. To run this application, insert the filename into the Application Parameters field of the Inbound Service that runs this application.

    We call Ring and Answer and then play the file using channel.FilePlayer.Play(). This plays the wav file contained in the applicationParameters argument, blocking until the wav file has finished playing. Note that we could have started played the file without blocking using the channel.FilePlayer.Start() method.

    Code:

    // An inbound application that plays a wav file (filename passed in) to the
    // caller then hangs up.
    //
    // Requires:
    // [applicationParameters = the wav filename]
    namespace InboundPlayWav
    
        open System
        open System.Threading
        open AMSClassLibrary
        open UASAppAPI
    
        // Possible return codes
        type ReturnCode =
            // Success Codes:
            | Success = 0
            // ... any positive integer
    
            // Fail Codes:
            // -1 to -99 reserved
            | ExceptionThrown = -100
            | PlayInterrupted = -101
    
        // The application class.
        // This must have the same name as the assembly and must inherit from either 
        // UASInboundApplication or UASOutboundApplication.
        // It must override the Run method.
        type InboundPlayWav() = 
            inherit UASInboundApplication()
    
            // This is the entry point for the application
            override obj.Run(channel:UASCallChannel, applicationParameters:string) : int = 
                
                obj.Trace.TraceInfo("In - appParms [{0}]", applicationParameters)
                let mutable reply = ReturnCode.Success
    
                try
                    // Ring for 2 seconds
                    channel.Ring(2) |> ignore
    
                    // Answer the call
                    if channel.Answer() = CallState.Answered then
    
                        obj.Trace.TraceInfo("Call answered")
    
                        if applicationParameters.Length = 0 then
                            channel.FilePlayer.Say("No wav file name was specified to play") |> ignore
                        elif channel.FilePlayer.Play(applicationParameters) <> FilePlayerCause.Normal then
                            obj.Trace.TraceError("Play failed or was interrupted")
                            reply <- ReturnCode.PlayInterrupted
    
                        channel.HangUp() |> ignore
                with 
                    | _ as e -> 
                        obj.Trace.TraceError("Exception caught {0}", e.Message)
                        reply <- ReturnCode.ExceptionThrown
    
                    
                obj.Trace.TraceInfo("Completed")
                (int)reply
                

Archive

The Aculab blog

News, views and industry insights from Aculab

  • Biometrics To Stop Hackers

    In today's digital era, cyber threats are far too common; data breaches are an ongoing danger, meaning robust security measures are essential. Traditional authentication methods such as passwords and PINs are increasingly vulnerable to hacking and cyber-attacks. However, there is a powerful tool to help the fight against cybercrime: biometric technology.

    Continue reading

  • Eliminating Barriers to Communication with Live Audio Translation for Phone Calls

    In an increasingly interconnected world, clear and effective communication is more essential than ever. That’s why Aculab intends to help break down language barriers and foster cross-cultural communications.

    Continue reading

  • The End of the PSTN in the US

    As the technical world has evolved, so has the way we communicate. The gradual, global transition away from the Public Switched Telephone Network (PSTN) is the most noticeable change in recent years. This begs the question, is the PSTN in the US headed towards a slow end as we transition into the digital era?

    Continue reading

  • Revolutionising the Landscape of Remote Authentication

    In a time where borders blur and workplaces extend beyond the confines of traditional offices, the significance of remote authentication has taken centre stage. As we advance, so does the need for secure and efficient ways to verify and authenticate our identity remotely. Finding the balance between security and user convenience is key when seeking to implement successful remote authentication.

     

    Continue reading

  • Choosing The Ideal Communication Platform: Key Considerations to Optimise Your Business

    Communication Platforms as a Service have become a necessity in the current digital age; allowing businesses to obtain frictionless means of communicating effectively. However, as technology rapidly evolves, so must communications. Much of the platforms on offer today are homogenous, so choosing the best fit for your business can be difficult. In this blog, we have shared some key points and trends for to consider, so your business can amplify communications and increase operational efficiency!

     

    Continue reading