android - 使用 Laravel 为 Android 提供 mp3 流

标签 android laravel streaming mp3 android-mediaplayer

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

对于 laravel 后端,我需要使用 JWT 来处理身份验证,因此在每个请求 header 上,我必须将“授权”字段设置为“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 代码即可流式传输文件。

关于android - 使用 Laravel 为 Android 提供 mp3 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37548096/

相关文章:

android - JSoup 不解析 Android 已知问题页面

Android NDK 和 Google Play 过滤

mysql - 如何使用 Eloquent Laravel 嵌套两个查询

javascript - 是否可以在浏览器中创建本地 JavaScript 代理?

Php 录制直播到文件

Golang 在我的直播中超时

android - 错误 : eglSurfaceAttrib not implemented

java - 从 JSON Java Android 中的嵌入式 MongoID 中获取字符串

javascript - Stripe Payment Element 加载时间慢

javascript - 使用 ajax 和 laravel 提交表单