phphtmlringcentral

Play an audio file from a incoming file without saving


I'm using the ringcentral-php SKD to retrieve call recordings. I'm attempting to get around saving the file before playing it. (Stream or play from temp file) This is the code.

$uri = 'https://media.devtest.ringcentral.com/restapi/v1.0/account/851921005/recording/15694407005/content';

$apiResponse = $platform->get($uri);

$mp3_file = $apiResponse->raw();

file_put_contents("recordings/recording_test.mp3", $mp3_file);//This is not allowed on the server//

echo '<audio controls>
<source src="recordings/recording_test.mp3" type="audio/mpeg">
    </audio>';

The goal is not to save the recordings, just play them on demand. Any ideas?


Solution

  • Concept

    You can output content directly to the browser with PHP. Instead of saving the file to disk, you'll send it as a response to the client's browser with headers.


    Static

    get_audio.php:

    $uri = 'https://media.devtest.ringcentral.com/restapi/v1.0/account/851921005/recording/15694407005/content';
    $apiResponse = $platform->get($uri);
    $mp3_file = $apiResponse->raw();
    
    header('Content-Type: audio/mpeg');
    
    echo $mp3_file;
    

    HTML:

    <audio controls>
        <source src="get_audio.php" type="audio/mpeg">
    </audio>
    

    Dynamic

    And of course you can pass parameters if you need to adjust which audio file to output dynamically:

    get_audio.php:

    if (!isset($_GET['audioId'])) {
        // Handle the error appropriately in production of course
        die('Audio ID is required');
    }
    
    $audioId = $_GET['audioId'];
    $uri = 'https://media.devtest.ringcentral.com/restapi/v1.0/account/851921005/recording/' . $audioId . '/content';
    
    $apiResponse = $platform->get($uri);
    $mp3_file = $apiResponse->raw();
    
    header('Content-Type: audio/mpeg');
    
    echo $mp3_file;
    
    

    HTML:

    <audio controls>
        <source src="get_audio.php?audioId=15694407005" type="audio/mpeg">
    </audio>