Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php header for .wav file download but cannot play in embed

Tags:

php

wav

I have to build the header for a .wav file for it to play in the element.

$filename =  basename($_GET['file']);

$pos = strrpos($file, '.');

$extension = ($pos !== false) ? substr($file, $pos) : '';

$mime_type = "";
switch ($extension) {
    case '.mp3':
        $mime_type = "audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3";
        break;
    case '.ulaw':
        $mime_type = "audio/basic";
        break;
    case '.gsm':
        $mime_type = "audio/x-gsm";
        break;
    case '.wav':
        $mime_type = "audio/x-wav, audio/wav";
        break;
}

if(file_exists($filename)){
    $handle = fopen($filename, "rb");

    header('Content-Description: File Transfer');
    header("Content-Transfer-Encoding: binary"); 
    header('Content-Type: '.$mime_type);
    header('Content-length: ' . filesize($filename));
    header('Content-Disposition: attachment;filename="' . $filename.'"');

    while (!feof($handle)) {
        echo fread($handle, 4096);
        flush();
    }
    fclose($handle);
}else{
    header("HTTP/1.0 404 Not Found");
}

This is called by www.example.com/listen?file=Test.en.wav

For now, when I go on that page, the file downloads and works (Half of what I want), but when I try :

<embed src="www.example.com/listen?file=Test.en.wav">

The player appears, but the file doesn't/can't play.

Edit : I would like to know if it is possible to make it play and how?

like image 245
Benoit Avatar asked Oct 22 '22 12:10

Benoit


1 Answers

Instead of using a switch/case block, why not use PHP's function mime_content_type()?

Example:

<?php
$file="/path/to/file.wav";
$mime_type=mime_content_type($file);
echo $mime_type;
?>

Output: audio/x-wav

like image 112
Jay Avatar answered Oct 27 '22 10:10

Jay