doubo1871 2013-05-13 14:36
浏览 73

提供一个mp3 / ogg文件碎片到html5音频

I'm trying to provide a audio file through a browser using HTML5 audio tag:

<audio preload="auto">
    <source src="<?php echo $song->getUrl('mp3'); ?>" type="audio/mpeg">
    <source src="<?php echo $song->getUrl('ogg'); ?>" type="audio/ogg">
    Please update your browser.
</audio>

I need to save traffic, so I thought about sending partial content this way:

$contentType = ($format == 'mp3') ? 'audio/mpeg' : 'audio/ogg';
$filePath = $song->getPath($format);
$fileLength = filesize($filePath);

$start = 0;
if(isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE'])) {
    $http_range = explode('-', substr($_SERVER['HTTP_RANGE'], strlen('bytes=')));
    $start = $http_range[0];
}

$remainingBytes = $fileLength - $start;

$length = min((512*1024), $remainingBytes);
$final = $start + $length;

header('HTTP/1.1 206 Partial Content');
header('Status: 206 Partial Content');
header('Content-Type: ' . $contentType);
header('Content-Disposition: inline;filename="listen.' . $format . '"');
header('Content-length: ' . $length);
header('Content-Transfer-Encoding: bytes');
header('Accept-Ranges: bytes');
header('Cache-Control: no-cache');
header('Content-Range: bytes ' . $start . '-' . $final . '/' . $fileLength);
echo file_get_contents($filePath, false, null, $start, $length);

The result of this is, in Chrome, the song being almost completely played (3.41 out of 3.47 seconds of a 9.1MB file). In firefox, the first 39 seconds played (I guess 512KB). In opera, a never-ending "loading" status.

  • 写回答

2条回答 默认 最新

  • douxue7196 2013-05-13 14:41
    关注

    I think you mistakenly calculate the size of the file

    $contentType = ($format == 'mp3') ? 'audio/mpeg' : 'audio/ogg';
    $filePath = $song->getPath($format);
    $fileLength = filesize($filePath);
    

    EDITED

    $format is file extension and not filepath AND

    filesize($filePath); // Do not returns file size
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试