Java 安卓在线音乐播放器
我尝试建立一个Android在线音乐播放器,可以同时下载和播放歌曲,用户可以在下载时间内听到音乐,然后才能完成下载。 我使用下面的下载类和MediaPlayer来启动音乐,但这个类仅在下载完成时工作,如果用户在完整下载应用程序与NullpointExption崩溃之前单击“播放”,是否有任何解决方案 下载课程简历:Java 安卓在线音乐播放器,java,android,Java,Android,我尝试建立一个Android在线音乐播放器,可以同时下载和播放歌曲,用户可以在下载时间内听到音乐,然后才能完成下载。 我使用下面的下载类和MediaPlayer来启动音乐,但这个类仅在下载完成时工作,如果用户在完整下载应用程序与NullpointExption崩溃之前单击“播放”,是否有任何解决方案 下载课程简历: public class downloader { private static boolean Stopdownloader = false;//use for stop down
public class downloader {
private static boolean Stopdownloader = false;//use for stop download
public static void Stop(boolean status) {
Stopdownloader = status;
}
public static void dl(final String downloadPath, final String filePath, final Ondownloadprogress lisener) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
int downloadedSize = 0;
int fileLength = 0;
URL url = new URL(downloadPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
File file = new File(filePath);
if (file.exists()) {
connection.setRequestProperty("Range", "bytes=" + file.length() + "-");
downloadedSize = (int) file.length();
}
connection.setRequestMethod("GET");
connection.setDoInput(true);
final int FILE_SIZE = connection.getContentLength();
connection.connect();
fileLength = connection.getContentLength() + downloadedSize;
BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
RandomAccessFile output = new RandomAccessFile(file, "rw");
output.seek(downloadedSize);
byte data[] = new byte[1024];
int count = 0;
int progress = 0;
while ((count = input.read(data, 0, 1024)) != -1
&& progress != 100)
{
if (Stopdownloader) {
break;
}
downloadedSize += count;
output.write(data, 0, count);
progress = (int) ((downloadedSize * 100) / fileLength);
final int ss = (int) ((downloadedSize * 100) / fileLength);
final float persent = ((float) progress / FILE_SIZE) * 100;
if (lisener != null) {
final int finalProgres = progress;
G.HANDLER.post(new Runnable() {
@Override
public void run() {
lisener.ondownload((int) ss, finalProgres, FILE_SIZE);
}
});
}
}
output.close();
input.close();
}
catch (MalformedURLException e) {}
catch (IOException e) {}
finally {}
}
});
thread.start();
}}
在主要活动中:
play.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
downloader.dl("http://MUSIC-URL","/temp.mp3", null);
downloader.Stop(false);
MediaPlayer Music = MediaPlayer.create(G.context, Uri.parse("/temp.mp3"));
Music.start();
Music.prepare();
}
});
你需要在开始前做好准备 android参考资料写得很好:
看看这篇教程,我想它也会让你有所进步。is/temp.mp3`文件路径有效吗?是的,文件创建和有效,下载完整的mediaplayer时正确启动,但我尝试同时播放音乐和下载文件谢谢回答,但如果在开始前准备媒体先下载完成,然后播放,但我尝试在完成前播放音乐文件。。。