Serve mp3 stream for android with Laravel

后端 未结 1 2081
清歌不尽
清歌不尽 2021-02-10 03:35

Here\'s my problem: I\'m writing a laravel backend which have to serve an mp3 file that had to be reproduced by using the android standard media player.

For the laravel

相关标签:
1条回答
  • 2021-02-10 04:27

    The problem: Response::download(...) doesn't produce a stream, so I can't serve my .mp3 file.

    The solution: As Symfony HttpFoundation doc. says in the serving file paragraph:

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

    The .mp3 files I need to serve are statics in the server and stored in "/storage/songs/" so I decided to use the BinaryFileResponse, and the method for serving .mp3 became:

    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);
    }
    

    The BinaryFileResponse automatically handle the requests and allow you to serve the file entirely (by making just one request with Http 200 code) or splitted for slower connection (more requests with Http 206 code and one final request with 200 code).
    If you have the mod_xsendfile you can use (to make streaming faster) by adding:

    BinaryFileResponse::trustXSendfileTypeHeader();
    

    The android code doesn't need to change in order to stream the file.

    0 讨论(0)
提交回复
热议问题