right  Talk To Us!

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