该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
//首先通过这个方法取得流
private InputStream getDataFromURL(Context context, String url) throws Exception {
URLConnection connection = new URL(url).openConnection();
connection.setConnectTimeout(STREAM_CONNECT_TIMEOUT);
connection.setReadTimeout(STREAM_READ_TIMEOUT);
return connection.getInputStream();
}
//然后开始缓冲数据
private void downloadMusic(String mediaUrl) throws Exception {
InputStream stream = getDataFromURL(mActivity, mediaUrl);
if (stream == null) {
nextMusic();
return;
}
//创建音乐文件,如果已经有了,把之前的删掉
downloadingMediaFile = new File(mActivity.getCacheDir(), downloadingFileName);
if (downloadingMediaFile.exists()) {
downloadingMediaFile.delete();
}
//下面就是从网络获取数据写到文件中,下载到200Kb以后开始播放
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
byte buf[] = new byte[10 * 1024];
int totalBytesRead = 0;
int numRead;
while ((numRead = stream.read(buf)) != -1) {
out.write(buf, 0, numRead);
totalBytesRead += numRead;
totalKbRead = totalBytesRead / 1024;
//缓冲到200Kb以后开始播放,此后每次收到数据都会调用此方法,不过不是开始播放,而是把数据加入到播放器中
if (totalKbRead >= 200)
startMediaPlayer();
}
isDownload = true;
stream.close();
startMediaPlayer();
}
//最后就是开始播放和装载缓冲数据的方法了
private void startMediaPlayer() {
//如果mediaPlayer是空的,那就是要新开始播放,否则就是装载缓冲数据
if (mediaPlayer == null) {
try {
mediaPlayer = createMediaPlayer(downloadingMediaFile);
Intent intent = new Intent(BROADCAST_ACTION_DOWNLOAD_MUSIC_DONE);
mActivity.sendBroadcast(intent);
//这里是开始播放
resume();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ((totalKbRead - loadedKb >= 200) || isDownload) {
//如果缓冲数据已经比上一次装载到播放器的数据多200Kb了或音乐已经下载完了,才会执行这里
try {
//我的问题就在这一块,每次装载的时候因为要重新设置数据源和prepare,音乐总会卡一下,虽然时间很短
//大概卡零点几秒左右的时间,但仔细听总能听出来
mediaPlayer.stop();
int currentPosition = mediaPlayer.getCurrentPosition();
mediaPlayer.reset();
FileInputStream fis = new FileInputStream(downloadingMediaFile);
mediaPlayer.setDataSource(fis.getFD());
mediaPlayer.prepare();
mediaPlayer.seekTo(currentPosition);
//判断一下是不是手动点了暂停的
if (!isPause) {
resume();
}
loadedKb = totalKbRead;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}