phpcurltext-to-speechrapidapi

Saving a file with curl and php


I am attempting to use an API from voicerss. The API itself appears to be working. My problem is when the API returns the data to me. In my past experience I have used APIS to retrieve bits of text or sometimes links to files which I can then download. This particular API is returning audio data. I can get it working in my firefox browser enough that I can send some text and I hear it converted to audio speech. In chrome browser it is completely broken and sends characters to the screen similar to this.

&&KZ��q<� ޤ)�ˆ��s�R�f8������.

I don't know curl but that's how the example was provided to me.

I have this code and it is known working in firefox 11. It just spits garbage to the screen in chrome 110.0.5481.77

What would work best for me is having the audio saved to a file. Everything I have found online has lead to failure. My though is. if I have the data saved to a file. The browser issues are irrelevant because it is trivial to to play an audio file in either browser.

$src = $_GET['src'];
$curl = curl_init();    
curl_setopt_array($curl, [
CURLOPT_URL => "https://voicerss-text-to-speech.p.rapidapi.com/?key=MYAPIKEY&src=$src&hl=en-us&r=0&c=mp3&f=8khz_8bit_mono",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
    "X-RapidAPI-Host: voicerss-text-to-speech.p.rapidapi.com",
    "X-RapidAPI-Key: MYAPIKEY"
],
]);

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

If anyone could help me to be able to save the audio to a file Id be grateful.


Solution

  • Lawrence guided me in the right direction

    Ultimately adding headers

    header('Content-Type: audio/mpeg'); header("Content-Disposition:inline;filename=audio.mp3");

    solved my issue