为 android 和 Laravel 提供 mp3 流

Serve mp3 stream for android with Laravel

这是我的问题:我正在编写一个 laravel 后端,它必须提供一个必须使用 android 标准媒体播放器复制的 mp3 文件。

对于 laravel 后端,我需要使用 JWT 来处理每个请求的身份验证 headers 我必须将 "Authorization" 字段设置为“Bearer {token}" .
laravel路由是"/songs/{id}",这样处理:

public function getSong(Song $song) {
    $file = new File(storage_path()."/songs/".$song->path.".mp3");

    $headers = array();
    $headers['Content-Type'] = 'audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3';
    $headers['Content-Length'] = $file->getSize();
    $headers['Content-Transfer-Encoding'] = 'binary';
    $headers['Accept-Range'] = 'bytes';
    $headers['Cache-Control'] = 'must-revalidate, post-check=0, pre-check=0';
    $headers['Connection'] = 'Keep-Alive';
    $headers['Content-Disposition'] = 'attachment; filename="'.$song->path.'.mp3"';

    $user = \Auth::user();
    if($user->activated_at) {
        return Response::download($file, $song->path, $headers);
    }
    \App::abort(400);
}

在 android 方面,我使用 MediaPlayer 以这种方式流式传输 mp3 文件:

media_player = new MediaPlayer();
    try {
        media_player.setAudioStreamType(AudioManager.STREAM_MUSIC);

        String token = getSharedPreferences("p_shared", MODE_PRIVATE).getString("token", null);
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + token);

        media_player.setDataSource(
            getApplicationContext(),
            Uri.parse(ConnectionHelper.SERVER + "/songs/" + song.getId()),
            headers
        );
    } catch (IOException e) {
        finish();
        Toast.makeText(
                Round.this,
                "Some error occurred. Retry in some minutes.",
                Toast.LENGTH_SHORT
        ).show();
    }
    media_player.setOnCompletionListener(this);
    media_player.setOnErrorListener(this);
    media_player.setOnPreparedListener(this);

但是每次我执行代码时,我都会在错误侦听器上得到额外的代码 -1005,这意味着 ERROR_CONNECTION_LOST

问题Response::download(...) 没有产生流,所以我无法提供服务我的 .mp3 文件。

解决方法: 正如 Symfony HttpFoundation doc. 在服务文件段落中所说:

"if you are serving a static file, you can use a BinaryFileResponse"

我需要提供的 .mp3 文件是服务器中的静态文件,存储在“/storage/songs/”中,所以我决定使用 BinaryFileResponse,服务 .mp3 的方法变为:

use Symfony\Component\HttpFoundation\BinaryFileResponse;

[...]

public function getSong(Song $song) {
    $path = storage_path().DIRECTORY_SEPARATOR."songs".DIRECTORY_SEPARATOR.$song->path.".mp3");

    $user = \Auth::user();
    if($user->activated_at) {
        $response = new BinaryFileResponse($path);
        BinaryFileResponse::trustXSendfileTypeHeader();

        return $response;
    }
    \App::abort(400);
}

BinaryFileResponse 自动处理请求并允许您完全处理文件(通过仅使用 Http 200 代码发出一个请求)或拆分以降低连接速度(使用 Http 206 代码的更多请求和使用 200 代码的最后一个请求) .
如果你有 mod_xsendfile 你可以通过添加来使用(使流式传输更快):

BinaryFileResponse::trustXSendfileTypeHeader();

无需更改 android 代码即可流式传输文件。