I'm creating an app using flutter where I'm retrieving audios from the AWS-s3 bucket. Before I retrieve the audio I check if the user has access to that file. Then I add the audio to the plugin "audioplayers" and the audio is played without problems but the duration of the audio is never loaded.
The problem with the duration is happening just with iPhone, using flutter, chrome and safari.
This is my PHP code to retrieve the audio, I have not added the permissions check because if I remove that part of the code the result is the same. I think the problem is in how I retrieve the audio file:
function printAudio($audioID)
{
$url = "my_file_url";
header_remove();
print_headers($url);
//header("Content-Length: " . filesize($url));
readfile($url);
}
function print_headers($url)
{
$headers = get_headers($url);
if ($headers != null) {
foreach ($headers as $header) {
print_if_needed($header);
//header($header);
}
}
}
function print_if_needed($header)
{
if (str_contains($header, "Accept-Ranges:")) {
header(strtolower($header));
return;
}
if (str_contains($header, "Content-Length:")) {
header(strtolower($header));
$fileSize = (int)str_replace("Content-Length: ", "", $header);
$rangeTo = $fileSize - 1;
header("Content-Range: bytes 0-$rangeTo/$fileSize");
return;
}
if (str_contains($header, "Content-Range:")) {
header(strtolower($header));
return;
}
if (str_contains($header, "Content-Type:")) {
header(strtolower($header));
return;
}
if (str_contains($header, "ETag:")) {
header(strtolower($header));
return;
}
if (str_contains($header, "Last-Modified:")) {
header(strtolower($header));
return;
}
}
I have added the content-range to check if that could solve the problem and the result is the same. As well I have tried using capitalized headers and lowercased.
I have tried retrieving the object using the AWS/s3 PHP API and the result is always the same, the audio can be played but the duration of the audio is never retrieved.
My Answer:
One possible solution to this issue could be to use a different method to retrieve the audio file in PHP. Instead of using readfile(), you can try using file_get_contents() to read the file contents and then output it to the response. This way, you can ensure that the necessary headers are being set correctly for the audio file.
Here is an example of how you can modify your printAudio() function using file_get_contents():
php
function printAudio($audioID)
{
$url = "my_file_url";
$fileContents = file_get_contents($url);
// Set the necessary headers
header("Content-Type: audio/mpeg");
header("Content-Length: " . strlen($fileContents));
// Output the file contents
echo $fileContents;
}
By using file_get_contents(), you can ensure that the correct headers are being set for the audio file, which may help in retrieving the duration of the audio in the audioplayers plugin in Flutter. Additionally, make sure that the audio file format is supported by the audioplayers plugin.
Rate this post
3 of 5 based on 8225 votesComments