0

我从服务器下载文件,有些大,有些小。

protected Long doInBackground(Object... params) {
        Context context = (Context) params[0];
        String name = (String) params[1];
        String urlString = (String) params[2];
        File mediadir = context.getDir("tvr", Context.MODE_PRIVATE);
        try {
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();
            connection.connect();
            int lenghtOfFile = connection.getContentLength();
            InputStream is = url.openStream();
            Log.d("DOWNLOAD NAME",name);
            File new_file = new File(mediadir, name);
            FileOutputStream fos = new FileOutputStream(new_file.getPath());
            byte data[] = new byte[1024];
            int count = 0;
            long total = 0;
            int progress = 0;
            while ((count=is.read(data)) != -1){
                total += count;
                int progress_temp = (int)total*100/lenghtOfFile;
                if(progress_temp%10 == 0 && progress != progress_temp){
                    progress = progress_temp;
                }
                fos.write(data, 0, count);
            }
            is.close();
            fos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.e("DOWNLOAD ERROR", e.toString());
        }
        return null;
    }

据我所知,我通过流下载文件并将数据流式传输到文件中。所以实际上文件是从第一个数据字节开始创建的。

现在,另一方面,我通过在目录中查找文件然后播放它们来播放内部目录中的文件:

mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setDisplay(holder);
FileInputStream fileInputStream = new FileInputStream(path);
mediaPlayer.setDataSource(fileInputStream.getFD());
fileInputStream.close();
mediaPlayer.prepare();
mediaPlayer.start();

现在这个问题是即使文件没有完全下载也会播放文件!

这是真的?如果是这样,在尝试播放之前我必须如何检查文件是否完整?

4

1 回答 1

3

Yes, this is a valid scenario, as in many cases your download speed will be slower than the reading and playing speed of the MediaPlayer.

Seeing as you're using an AsyncTask, you can fix this problem by calling the playing code in the onPostExecute() method, as that only runs after all work in the doInBackground() method has completed.

于 2013-02-26T13:19:05.200 回答