Getting Remote Audio File
I'm working on a Laravel API project that accepts audio file input as a remote url. I need to access this file and extract the duration metadata.
To achieve the duration I'm using php wapmorgan\Mp3Info\Mp3Info; library. The library works fine for local files but fails for remote files.
My challenge is that all efforts to get the remote file fails. I've tried:
-
php cURL - Laravel's Http client
- PHP's
php file_get_contentsandphp fopenfunctions
The above 3 methods are failing with the message:
[2022-04-28 09:33:26] local.ERROR: fopen(http://localhost:8000/storage/audios/jo4christ48-at-yahoocom/single-voice-call.mp3): Failed to open stream: HTTP request failed!
...
Also, the request seems quite slow. Sometimes, I terminate the request otherwise, nothing else works.
Here's my code for fetching the remote file and extracting the duration metadata.
/**
* calculates the units for remote files
*
* @param int $numbers_count
* @param string $file_url
* @return array
*/
protected function calculate_units_remote(int $numbers_count, string $file_url)
{
// get the file
// $ch = curl_init();
// curl_setopt($ch, CURLOPT_HEADER, 0);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_URL, $file_url);
// $file = curl_exec($ch);
// curl_close($ch);
// $response = Http::get($file_url);
// if (!$response->successful()) {
// return [
// 'status' => false,
// 'message' => 'The remote file cannot be reached.'
// ];
// }
// $file = $response->body();
$file = file_get_contents($file_url);
if (!$file) {
return [
'status' => false,
'message' => 'The remote file cannot be reached.'
];
}
// get the duration of the remote file
$file = new Mp3Info($file);
$duration = $file->duration;
// get user plan
$plan = Auth::user()->user_plan()->plan ?? Plan::where('type', 2)
->where('default', true)->first();
$units_per_second = $plan->units_per_second;
$units = $units_per_second * $duration * $numbers_count;
return [
'status' => true,
'units' => ceil($units)
];
}
The above function is called in a controller as show below:
...
// calculate units
$units = $this->calculate_units_remote(count($unique_numbers), $data['file']);
...
Note: I've enabled the allow_file_open extension in the init file and allowed incoming request on firewall (ufw) as recommended by some threads on stackoverflow.
Please or to participate in this conversation.