Documentation ¶
Overview ¶
Package play provides a set of tools for feature-rich audio playbacks and IVR primitives.
Index ¶
- Constants
- Variables
- type MatchResult
- type OptionFunc
- func DigitTimeouts(first, inter, overall time.Duration) OptionFunc
- func InvalidPrependURI(uri ...string) OptionFunc
- func MatchAny() OptionFunc
- func MatchDiscrete(list []string) OptionFunc
- func MatchFunc(f func(string) (string, MatchResult)) OptionFunc
- func MatchHash() OptionFunc
- func MatchLen(length int) OptionFunc
- func MatchLenOrTerminator(length int, terminator string) OptionFunc
- func MatchNone() OptionFunc
- func MatchTerminator(terminator string) OptionFunc
- func NoExitOnDTMF() OptionFunc
- func PlaybackStartTimeout(timeout time.Duration) OptionFunc
- func Replays(count int) OptionFunc
- func URI(uri ...string) OptionFunc
- type Options
- type Result
- type Session
- type Status
Examples ¶
Constants ¶
const AllDTMF = "0123456789ABCD*#"
AllDTMF is a string which contains all possible DTMF digits.
Variables ¶
var ( // DefaultPlaybackStartTimeout is the default amount of time to wait for a playback to start before declaring that the playback has failed. DefaultPlaybackStartTimeout = 2 * time.Second // DefaultMaxPlaybackTime is the default maximum amount of time any playback is allowed to run. If this time is exeeded, the playback will be cancelled. DefaultMaxPlaybackTime = 10 * time.Minute // DefaultFirstDigitTimeout is the default amount of time to wait, after the playback for all audio completes, for the first digit to be received. DefaultFirstDigitTimeout = 4 * time.Second // DefaultInterDigitTimeout is the maximum time to wait for additional // digits after the first is received. DefaultInterDigitTimeout = 3 * time.Second // DefaultOverallDigitTimeout is the default maximum time to wait for a // response, after the playback for all audio is complete, regardless of the // number of received digits or pattern matching. DefaultOverallDigitTimeout = 3 * time.Minute // DigitBufferSize is the number of digits stored in the received-digit // event buffer before further digit events are ignored. NOTE that digits // overflowing this buffer are still stored in the digits received buffer. // This only affects the digit _signaling_ buffer. DigitBufferSize = 20 )
var Logger = log15.New()
Logger defaults to a discard handler (null output). If you wish to enable logging, you can set your own handler like so:
ari.Logger.SetHandler(log15.StderrHandler)
Functions ¶
This section is empty.
Types ¶
type MatchResult ¶
type MatchResult int
MatchResult indicates the status of a match for the received DTMF of a playback
const ( // Incomplete indicates that there are not enough digits to determine a match Incomplete MatchResult = iota // Complete indicates that a match was found and the current DTMF pattern is complete Complete // Invalid indicates that a match cannot befound from the current DTMF received set Invalid )
type OptionFunc ¶
OptionFunc defines an interface for functions which can modify a play session's Options
func DigitTimeouts ¶
func DigitTimeouts(first, inter, overall time.Duration) OptionFunc
DigitTimeouts sets the digit timeouts. Passing a negative value to any of these indicates that the default value (shown in parentheses below) should be used.
First digit timeout (4 sec): The time (after the stop of the audio) to wait for the first digit to be received
Inter digit timeout (3 sec): The time (after receiving a digit) to wait for the _next_ digit to be received
Overall digit timeout (3 min): The maximum amount of time to wait (after the stop of the audio) for digits to be received, regardless of the digit frequency
func InvalidPrependURI ¶
func InvalidPrependURI(uri ...string) OptionFunc
InvalidPrependURI sets a prepend URI set to be played when Replay count > 0, such as when a user has entered and invalid DMTF sequence.
func MatchAny ¶
func MatchAny() OptionFunc
MatchAny indicates that the playback should be considered Matched and terminated if any DTMF digit is received during the playback or post-playback time.
func MatchDiscrete ¶
func MatchDiscrete(list []string) OptionFunc
MatchDiscrete indicates that the playback should be considered Matched and terminated if the received DTMF digits match any of the discrete list of strings.
func MatchFunc ¶
func MatchFunc(f func(string) (string, MatchResult)) OptionFunc
MatchFunc uses the provided match function to determine when the playback should be terminated based on DTMF input.
func MatchHash ¶
func MatchHash() OptionFunc
MatchHash indicates that the playback should be considered Matched and terminated if it contains a hash (#). The hash (and any subsequent digits) is removed from the final result.
func MatchLen ¶
func MatchLen(length int) OptionFunc
MatchLen indicates that the playback should be considered Matched and terminated if the given number of DTMF digits are receieved.
func MatchLenOrTerminator ¶
func MatchLenOrTerminator(length int, terminator string) OptionFunc
MatchLenOrTerminator indicates that the playback should be considered Matched and terminated if the given number of DTMF digits are receieved or if the given terminator is received. If the terminator is present, it and any subsequent digits will be removed from the final result.
func MatchNone ¶
func MatchNone() OptionFunc
MatchNone indicates that the playback should never be terminated due to DTMF
func MatchTerminator ¶
func MatchTerminator(terminator string) OptionFunc
MatchTerminator indicates that the playback shoiuld be considered Matched and terminated if it contains the provided Terminator string. The terminator (and any subsequent digits) is removed from the final result.
func NoExitOnDTMF ¶
func NoExitOnDTMF() OptionFunc
NoExitOnDTMF disables exiting the playback when DTMF is received. Note that this is just a wrapper for MatchFunc(nil), so it is mutually exclusive with MatchFunc; whichever comes later will win.
func PlaybackStartTimeout ¶
func PlaybackStartTimeout(timeout time.Duration) OptionFunc
PlaybackStartTimeout overrides the default playback start timeout
func Replays ¶
func Replays(count int) OptionFunc
Replays sets the number of replays of the audio sequence before exiting
type Options ¶
type Options struct {
// contains filtered or unexported fields
}
Options represent the various playback options which can modify the operation of a Playback.
func NewDefaultOptions ¶
func NewDefaultOptions() *Options
NewDefaultOptions returns a set of options which represent reasonable defaults for most simple playbacks.
func NewPlay ¶
func NewPlay(ctx context.Context, p ari.Player, opts ...OptionFunc) (*Options, error)
NewPlay creates a new audio Options suitable for general audio playback
func NewPrompt ¶
func NewPrompt(ctx context.Context, p ari.Player, opts ...OptionFunc) (*Options, error)
NewPrompt creates a new audio Options suitable for prompt-style playback-and-get-response situations
func NewPromptOptions ¶
func NewPromptOptions() *Options
NewPromptOptions returns a set of options which represent reasonable defaults for most prompt playbacks. It will terminate when any single DTMF digit is received.
func (*Options) ApplyOptions ¶
func (o *Options) ApplyOptions(opts ...OptionFunc) (err error)
ApplyOptions applies a set of OptionFuncs to the Playback
type Result ¶
type Result struct { // Duration indicates how long the playback execution took, from start to finish Duration time.Duration // DTMF records any DTMF which was received by the playback, as modified by any match functions DTMF string // Error indicates any error encountered which caused the termination of the playback Error error // MatchResult indicates the final result of any applied match function for DTMF digits which were received MatchResult MatchResult // Status indicates the resulting status of the playback, why it was stopped Status Status // contains filtered or unexported fields }
Result describes the result of a playback operation
type Session ¶
type Session interface { // Add appends a set of AudioURIs to a Play session. Note that if the Play session // has already been completed, this will NOT make it start again. Add(list ...string) // Done returns a channel which is closed when the Play session completes Done() <-chan struct{} // Err waits for a session to end and returns its error Err() error // StopAudio stops the playback of the audio sequence (if there is one), but // unlike `Stop()`, this does _not_ necessarily terminate the session. If // the Play session is configured to wait for DTMF following the playback, // it will still wait after StopAudio() is called. StopAudio() // Result waits for a session to end and returns its result Result() (*Result, error) // Stop stops a Play session immediately Stop() }
Session describes a structured Play session.
func Play ¶
func Play(ctx context.Context, p ari.Player, opts ...OptionFunc) Session
Play plays a set of media URIs. Pass these URIs in with the `URI` OptionFunc.
Example ¶
c := &arimocks.Client{} key := ari.NewKey(ari.ChannelKey, "exampleChannel") h := ari.NewChannelHandle(key, c.Channel(), nil) res, err := Play(context.TODO(), h, URI("sound:tt-monkeys", "sound:vm-goodbye"), ).Result() if err != nil { fmt.Println("Failed to play audio", err) return } if len(res.DTMF) > 0 { fmt.Println("Got a DTMF during playback:", res.DTMF) }
Output:
Example (Async) ¶
c := &arimocks.Client{} key := ari.NewKey(ari.ChannelKey, "exampleChannel") h := ari.NewChannelHandle(key, c.Channel(), nil) bridgeSub := h.Subscribe(ari.Events.ChannelEnteredBridge) defer bridgeSub.Cancel() sess := Play(context.TODO(), h, URI("characters:ded", "sound:tt-monkeys", "number:192846", "digits:43"), ) select { case <-bridgeSub.Events(): fmt.Println("Channel entered bridge during playback") case <-sess.Done(): if sess.Err() != nil { fmt.Println("Prompt failed", sess.Err()) } else { fmt.Println("Prompt complete") } }
Output:
func Prompt ¶
func Prompt(ctx context.Context, p ari.Player, opts ...OptionFunc) Session
Prompt plays the given media URIs and waits for a DTMF response. The received DTMF is available as `DTMF` in the Result object. Further customize the behaviour with Match type OptionFuncs.
Example ¶
c := &arimocks.Client{} key := ari.NewKey(ari.ChannelKey, "exampleChannel") h := ari.NewChannelHandle(key, c.Channel(), nil) res, err := Prompt(context.TODO(), h, URI("tone:1004/250", "sound:vm-enter-num-to-call", "sound:astcc-followed-by-pound"), MatchHash(), // match any digits until hash Replays(3), // repeat prompt up to three times, if no match ).Result() if err != nil { fmt.Println("Failed to play", err) return } if res.MatchResult == Complete { fmt.Println("Got valid, terminated DTMF entry", res.DTMF) } // hash is automatically trimmed from res.DTMF
Output:
Example (Custom) ¶
db := mockDB{} c := &arimocks.Client{} key := ari.NewKey(ari.ChannelKey, "exampleChannel") h := ari.NewChannelHandle(key, c.Channel(), nil) res, err := Prompt(context.TODO(), h, URI("sound:agent-user"), MatchFunc(func(in string) (string, MatchResult) { // This is a custom match function which will // be run each time a DTMF digit is received pat := strings.TrimSuffix(in, "#") user := db.Lookup(pat) if user == "" { if pat != in { // pattern was hash-terminated but no match // was found, so there is no match possible return pat, Invalid } return in, Incomplete } return pat, Complete }), ).Result() if err != nil { fmt.Println("Failed to play prompt", err) return } if res.MatchResult == Complete { fmt.Println("Got valid user", res.DTMF) }
Output:
type Status ¶
type Status int
Status indicates the final status of a playback, be it individual of an entire sequence. This Status indicates the reason the playback stopped.
const ( // InProgress indicates that the audio is currently playing or is staged to play InProgress Status = iota // Cancelled indicates that the audio was cancelled. This cancellation could be due // to anything from the control context being closed or a DTMF Match being found Cancelled // Failed indicates that the audio playback failed. This indicates that one // or more of the audio playbacks failed to be played. This could be due to // a system, network, or Asterisk error, but it could also be due to an // invalid audio URI. Check the returned error for more details. Failed // Finished indicates that the playback completed playing all bound audio // URIs in full. Note that for a prompt-style execution, this also means // that no DTMF was matched to the match function. Finished // Hangup indicates that the audio playback was interrupted due to a hangup. Hangup // Timeout indicates that audio playback timed out. It is not known whether this was due to a failure in the playback, a network loss, or some other problem. Timeout )