Play a random audio file on incoming call using Twilio Studio

58 Views Asked by At

I'm setting up a new project in Twilio Studio. I'd like incoming callers to hear one of ten different audio files at the beginning of the call. I have the sense I'm generating a random number and then assigning an audio file to that number to be played - I just don't know how to do this.

I would like to be able to number my audio files e.g. 1.mp3, 2.mp3, 3.mp3 etc. and then the random number that is generated somehow is passed into the URL of the played audio file so that it plays the corresponding audio file.

I found this support article: https://www.twilio.com/docs/studio/widget-library/run-function#example

It describes a random number generator but I have the sense that (1) this is too complex a solve (I could be wrong) and (2) I can't see a way to generate that number without user input and pass that number onto the URL for the audio file to be played.

1

There are 1 best solutions below

0
IObert On

You are on the right track, this can be done with Functions and then using the response to pass it in the "Say/Play Widget".

Studio itself is not capable to generated random numbers.

This is the minimal working example:

Studio Flow

Function code (derived from here):

exports.handler = function(context, event, callback) {
  const urls = [
    "https://demo.twilio.com/docs/classic.mp3",
    "https://api.twilio.com/cowbell.mp3"
  ];
  const randomIndex = Math.floor(Math.random() * urls.length);

  return callback(null, urls[randomIndex]);
};