Search code examples
twiliotwilio-phptwilio-twiml

Play music while waiting an answer in TWIML <dial>


How to dial numbers and diffuse a music to the caller while waiting a successful connexion ?

The code below waits the music to end before doing the <dial> (which is logic)

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Play>http://com.twilio.music.ambient.s3.amazonaws.com/gurdonark_-_Plains.mp3</Play>
    <Dial timeout="10" callerId="+1234567890">
        <Number url="whisper?id=1">+1122334455</Number>
        <Number url="whisper?id=2">+1122334466</Number>
        <Number url="whisper?id=3">+1122334477</Number>
    </Dial>
</Response>

NB: It would be nice NOT to use conference functionalities. Something with <Enqueue> maybe ?


Solution

  • Twilio developer evangelist here.

    You could do this with <Enqueue>. Here's how it would work:

    You would need replace the TwiML that <Play>s and then <Dial>s. This would have to be a dynamic action as you would need to make the three simultaneous calls using the REST API instead of TwiML. The TwiML that you would return would put your original caller into a queue as you suggest and play them music. In PHP that would look a bit like:

    <?php
    // Get the PHP helper library from twilio.com/docs/php/install
    require_once '/path/to/vendor/autoload.php';
    use Twilio\Rest\Client;
    
    // Your Account Sid and Auth Token from twilio.com/user/account
    $sid = "your_account_sid";
    $token = "your_auth_token";
    $client = new Client($sid, $token);
    
    $numbers = array('+1122334455', '+1122334466', '+1122334477');
    
    foreach ($numbers as $number) {
      $call = $client->calls->create(
          $number, $YOUR_CALLER_ID,
          array("url" => "http://example.com/dial_queue")
      );
    }
    
    header("content-type: text/xml");
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    ?>
    <Response>
      <Enqueue waitUrl="http://com.twilio.music.ambient.s3.amazonaws.com/">
        dialling
      </Enqueue>
    </Response>
    

    At the URL http://example.com/dial_queue you would need to return TwiML that dials the callee into the original caller. You have a whisper URL in your original example, which you can achieve by inlining that into the TwiML.

    <Response>
      <Say>Your custom message</Say>
      <Dial>
        <Queue>dialling</Queue>
      </Dial>
    </Response>
    

    Note that you dial the name of the <Queue> that you used in the original <Enqueue>. If this system will be used for more than one caller, then you probably need to generate unique queue names for them.

    The final things to do would then be to cancel the other two calls once a call connects and cancel the queue if none of the calls answer. I will leave that to you as I'm sure there's many ways you could achieve it with your own setup.

    Let me know if that helps at all.