Search code examples
twiliotwilio-phptwilio-api

Embed twilio recording?


Can someone recommend the best way of embedding a Twilio recording onto a web-site?

I'm talking about the Twilio recording that's hosted on the Twilio servers.

For now I'm just using the below PHP function I wrote to download the file and then figure out embedding on my side, but may be there's an easier way?

function download_recording_from_twilio($url) {

  // the file_name is everything after the twilio.com/ with an added .mp3 at the end
  $word_after_which_we_extract = "twilio.com/";

  // what is the beginning position of this word?
  $begPos = strpos($url, $word_after_which_we_extract);

  // beginning position is the beginning of the word plus the word length
  $begPos += strlen($word_after_which_we_extract);

  // everything after twilio.com/
  $everything_after = substr($url, $begPos, strlen($url));

  // position of the last / in $everything_after
  $last_slash = strrpos($url, "/");

  // everything after the last slash
  $everything_after_last_slash = substr($url, $last_slash, strlen($url));

  // full filepath
  $full_path = $everything_after.".mp3";

  // create final filename
  $file_name = $everything_after_last_slash.".mp3";

  $source = "https://api.twilio.com/".$full_path;
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $source);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, 'ecdhe_rsa_aes_128_gcm_sha_256');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_VERBOSE,true);
  $data = curl_exec ($ch);
  $error = curl_error($ch);
  curl_close ($ch);

  $destination = ".".$file_name;
  $file = fopen($destination, "w+");
  fputs($file, $data);
  fclose($file);
}

Thank you


Solution

  • You can use the <audio> element in your web page (https://developer.mozilla.org/en/docs/Web/HTML/Element/audio).

    For the src attribute, if you'd like to play the recordings in WAV format you can request against Twilio's 'recordings api' with a link like this

    https://api.twilio.com/2010-04-01/Accounts/ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Recordings/RExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.wav?Download=false

    where RExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx is the RECORDING SID

    Change the .wav to .mp3 and you'll play in MP3 format.

    Also, observe the Download=false query string parameter.