【发布时间】:2016-09-29 14:34:57
【问题描述】:
这是我的问题:我正在编写一个 laravel 后端,它必须提供一个 mp3 文件,该文件必须使用 android 标准媒体播放器进行复制。
对于 laravel 后端,我需要使用 JWT 来处理身份验证,因此对于每个请求标头,我必须将“授权”字段设置为“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。
【问题讨论】:
标签: android laravel streaming mp3 android-mediaplayer