1

我有一个用于流式传输音频文件的网站。主要是MP3和OGG。几个月以来,我自己处理(PHP)蒸汽部分(在它是 apache2 之前)。首先,我使用多媒体音频文件的切片二进制响应(用于内存分配)进行正常的 200 OK 响应。它工作正常,但我的所有音频都获得了 Infinity 持续时间。根据这个问题,我昨天更新了流媒体部分。

现在,我遇到了我能想象到的最奇怪的错误之一。我的代码重构在 MP3 上运行得非常好,但在 OGG 上却不行......

这是我的 Stream 课程。

<?php
class Stream extends Response
{
    protected $filepath;
    protected $delete;
    protected $range = ['from' => 0, 'to' => null];

    public function __construct($filePath, $delete = false, $range = NULL)
    {
        $this->delete = $delete;
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($finfo, $filePath);
        $size = filesize($filePath);

        $this->headers['Content-Type'] = $mimeType;
        $this->headers['Content-Length'] = $size;
        $this->headers['Accept-Ranges'] = 'bytes';
        $this->headers['Content-Transfer-Encoding'] = 'binary';
        unset($finfo, $mimeType);

        $this->code = 200;
        $this->range['to'] = $size - 1;

        if ($range !== NULL) {
            if (preg_match('/^bytes=\d*-\d*(,\d*-\d*)*$/i', $range) === false) {
                $this->code = 416;
            } else {
                $ranges = explode(',', substr($range, 6));
                foreach ($ranges as $rangee) {
                    $parts = explode('-', $rangee);
                    $this->range['from'] = intval($parts[0]);
                    $this->range['to'] = intval($parts[1]);

                    if (empty($this->range['to'])) {
                        $this->range['to'] = $size - 1;
                    }
                    if ($this->range['from'] > $this->range['to'] || $this->range['to'] >= $size) {
                        $this->code = 416;
                    }
                }
                $this->code = 206;
            }

        }

        if ($this->code === 416) {
            $this->headers = ['Content-Range' => 'bytes */{' . $size . '}'];
        } elseif ($this->code === 206) {
            $this->headers['Content-Range'] = 'bytes {' . $this->range['from'] . '}-{' . $this->range['to'] . '}/{' . $size . '}';
        }

        $this->filepath = $filePath;
    }

    public function show()
    {
        http_response_code($this->code);

        foreach ($this->headers as $header => $value) {
            header($header . ': ' . $value);
        }

        $file = fopen($this->filepath, 'r');
        fseek($file, $this->range['from']);

        $interval = $this->range['to'] - $this->range['from'];
        $outputBufferInterval = 4 * 1000;
        
        if ($interval < $outputBufferInterval) {
            $outputBufferInterval = $interval;
        }

        ob_start();
        while ($interval > 0) {
            echo fread($file, $outputBufferInterval);
            $interval -= $outputBufferInterval;
            ob_flush();
        }
        fclose($file);
        ob_end_clean();
        
        if ($this->delete) {
            unlink($this->filepath);
        }
    }
}

我对 HTTP_RANGE 有点困惑。谢谢,

4

0 回答 0