Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
781 views
in Technique[技术] by (71.8m points)

javascript - audio duration in Safari always returning infinity when streaming through PHP

For some reason in Safari (and no other major browser), when I serve an MP3 via PHP through an Audio context in JavaScript, the duration of the MP3 is always returned as infinity.

This problem has stumped me for the last few days and after reading a few links (including this one) in search for a solution, I have not progressed at all.


My code

PHP:

$path = "path/to/file.mp3";
$file = [
    "path"      => $path,
    "size"      => filesize($path),
    "bitrate"   => $bitrate
];

header("Accept-Ranges: bytes", false);
header("Content-Length: " . $file["size"], false);
header("Content-Type: audio/mpeg", false);

echo file_get_contents($file["path"]);

exit;

JavaScript:

var audio = new Audio(url);
// returns infinite on Safari
// returns 312.27311 on Chrome and Firefox (which is correct)
console.log(audio.duration);

I'm still yet to figure out why this problem is only in Safari and what is causing it in the first place, so if anyone has a solution it would be much appreciated!

Cheers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After much investigation like yourself I finally figured it out.

The first request Safari sends has the header:

Range: bytes=0-1

It's your job to respond "correctly" so that Safari will send additional requests to fetch the rest of the file.

Here is my example of the "correct" headers:

Content-Length: 2
Accept-Ranges: bytes
Content-Range: bytes 0-1/8469
(Make sure you set response status to 206!)
(8469 is the Content-Length of the entire file)

What happens after that is somewhat magical - Safari sends a follow up request that has this header:

Range: bytes=0-8468

And you should respond "correctly" like with these headers:

Content-Length: 8469
Accept-Ranges: bytes
Content-Range: bytes 0-8468/8469
(Again, status 206!)

I hope this solves it for you, since I spent many hours searching to no avail. I eventually realized I needed to adjust my server to handle requests where the Range header is present.

I used this commit to help me understand what the "correct" response is: https://github.com/jooby-project/jooby/commit/142a933a31b9d8742714ecd38475d90e563314f7


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...