我正在尝试使用媒体播放器播放视频,同时在SD卡上下载。我从SD卡给出了setdatasource ..媒体播放器播放视频,但几秒后停止视频,但媒体播放器仍在播放,但内容正在休息。如何在停止播放的地方再次播放视频?
private void downloadVideo(String url) {
try {
URL url1 = new URL(url);
long startTime = System.currentTimeMillis();
Log.i("TAG", "image download beginning: " + url);
URLConnection conn = url1.openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(30000);
File path = android.os.Environment.getExternalStorageDirectory();
InputStream is = conn.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File directories = new File(path + "/sequence/");
if (!directories.exists()) {
directories.mkdirs();
}
FileOutputStream outStream = new FileOutputStream(new File(
directories, "test2.mp4"));
byte[] buff = new byte[5 * 1024];
// byte[] buff = new byte[1024 * 24];
int len;
while ((len = inStream.read(buff)) != -1) {
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
Log.i("TAG",
"download completed in "
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (MalformedURLException e) {
Log.d("Malformed", e.toString());
} catch (IOException e) {
Log.d("IOException", e.toString());
}
}
播放视频的代码
Runnable task = new Runnable() {
public void run() {
try {
File path = android.os.Environment
.getExternalStorageDirectory();
// http://www.pocketjourney.com/downloads/pj/video/famous.3gp
// http://www.youtube.com/watch?v=Fvh38W4yKvc
// http://mconnect123456.s3.amazonaws.com/4532happyfit2.mp4
mp.reset();
mp.setDataSource(path + "/sequence/test2.mp4");
// mp.setDataSource("http://mconnect123456.s3.amazonaws.com/4532happyfit2.mp4");
mp.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
while (!mp.isPlaying()) {
Log.d("Playing", "playing");
}
}
};
worker.schedule(task, 5, TimeUnit.SECONDS);
答案 0 :(得分:1)
我不相信这是完成你想要做的事情的最好方法。 MediaPlayer
认为它正在播放本地文件,并且不会像网络播放一样正确地缓冲数据。
我建议在设备上创建本地代理服务器。然后,您可以将MediaPlayer
中的setDataSource
本地主机URI传递给您的代理,并在流式传输时缓存数据。请参阅我的回答here以获取更多信息,如果您在实施时遇到问题,请随时提出问题。