3

Using Twilio for an interactive art exhibition where you call the number and listen to the audio in the gallery. I'd like for incoming callers to not always hear the same 20-30 seconds of audio at the beginning of the audio file. Is it possible to provide 3-4 different audio files and one of them is randomly selected to Play for an incoming call. Or even to randomize the start time on the single audio file would work too.

I've searched everyone without much luck.

Code I'm using for the basic function is below.

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Play> https://dl.dropboxusercontent.com/s/qt0l2zjrlssj3nv/CMCA-PHONE-01.mp3 </Play>
</Response>

1 Answers1

4

Twilio evangelist here.

No built in way to do this but you could definitely generate the TwiML dynamically and randomly select the URL to include in the <Play> verb.

If you're not stoked about having to host all that yourself, Twilio Functions give you a way to write a bit of Node that could generate it.

For example, you could make an array that contains the n URL's, then use Math.random to pick a random item in that array:

exports.handler = function(context, event, callback) {
  var items = [
    'http://www.example.com/1.mp3',
    'http://www.example.com/2.mp3',
    'http://www.example.com/3.mp3',
    'http://www.example.com/4.mp3'];

  var item = items[Math.floor(Math.random()*items.length)];

  var twiml = new Twilio.twiml.VoiceResponse()
  twiml.play(item);
  console.log(twiml.toString())
  callback(null, twiml);
};

Hope that helps.

Devin Rader
  • 10,260
  • 1
  • 20
  • 32
  • 1
    Thanks @devin-rader. I watched the video on the Functions page. Made the adjustments to the Configure page it says to do and tried to implement your code (thank you!). Getting an application error. I've selected "Incoming Voice Calls" for the event. The code I have in there is: https://jsfiddle.net/onedynamicsystem/o3pg4zwb/#&togetherjs=eMpSO0DduL – Justin Levesque Mar 22 '19 at 21:27
  • 1
    Updated your jsfiddle. – Devin Rader Mar 22 '19 at 21:37
  • Whoa. Seriously. Thank you. I'll leave the code here for anyone else that might help: https://jsfiddle.net/onedynamicsystem/o3pg4zwb/#&togetherjs=eMpSO0DduL – Justin Levesque Mar 22 '19 at 21:41