4

I'm trying to serve a WAV file using PHP, and I want it to play rather than download. I'm setting up the headers like this:

$path = "wav.wav";
header('Accept-Ranges: bytes');
header('Connection: keep-alive');
header('Content-Length: ' . filesize($path));
header("Content-Type: audio/wav");
header("Content-Duration: 00:00:22.046");
readfile($path);
exit();

this works perfectly on chrome, IE, firefox, but not on safari 9 on mac (safari 8 did work). When I test I get no response headers at all!

this is a test link you can see for yourself: http://staging-new-play.idomoo.com/couchbase_test/t3.php

any ideas?

Moshe Shaham
  • 15,448
  • 22
  • 74
  • 114
  • In my experience when a file tries to download rather than autoplay it usually means that the machine doesn't know what to do with it. Does the computer you're testing Safari with have WAV files registered to play with a certain app? – tbernard Dec 23 '15 at 07:54
  • yes, safari does usually play wav files – Moshe Shaham Dec 23 '15 at 08:14
  • What was the answer for getting Mac Safari to play audio files? – Ryan Feb 20 '19 at 17:30
  • I finally got mine working here: https://stackoverflow.com/a/54796154/470749 – Ryan Feb 20 '19 at 22:24

3 Answers3

1

you need to send partial content

$file = "wav.wav";
$bufferSize = 2097152;

$filesize = filesize($file);
$offset = 0;
$length = $filesize;
if (isset($_SERVER["HTTP_RANGE"])) {
    preg_match("/bytes=(\d+)-(\d+)?/", $_SERVER["HTTP_RANGE"], $matches);
    $offset = intval($matches[1]);
    $end = $matches[2] || $matches[2] === "0" ? intval($matches[2]) : $filesize - 1;
    $length = $end + 1 - $offset;
    header("HTTP/1.1 206 Partial Content");
    header("Content-Range: bytes $offset-$end/$filesize");
}
header("Content-Type: " . mime_content_type($file));
header("Content-Length: $filesize");
header("Accept-Ranges: bytes");
$file = fopen($file, "r");
fseek($file, $offset);
ini_set("memory_limit", "-1");
while ($length >= $bufferSize)
{
    print(fread($file, $bufferSize));
    $length -= $bufferSize;
}
if ($length) print(fread($file, $length));
fclose($file);
Mauro Sala
  • 1,166
  • 2
  • 12
  • 33
0

Safari needs Content-Range: in order to play wav files.

Add this line:

header("Content-Range: something");
Phiter
  • 14,570
  • 14
  • 50
  • 84
0

I would try to drop some unnecessary headers (Accept-Ranges and Connection) and add a Content-Transfer-Encoding header:

header("Content-Length: " . filesize($path));
header("Content-Type: audio/wav");
header("Content-Duration: 00:00:22.046");
header("Content-Transfer-Encoding: binary");
huysentruitw
  • 27,376
  • 9
  • 90
  • 133