从URL下载视频并将其存储在Android设备中

时间:2015-12-03 19:00:54

标签: java android video

我有以下代码从网址下载视频:

String videoUrl =“https://www.youtube.com/watch?v=hS5CfP8n_js”;

private class LongOperation extends AsyncTask<String, Void, String> {
    private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
    private final int TIMEOUT_CONNECTION = 5000;//5sec
    private final int TIMEOUT_SOCKET = 30000;//30sec
    private String TAG = "TAG";

    @Override
    protected void onPreExecute() {
        dialog.setMessage("Downloading...");
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            url = new URL(videoUrl);
            long startTime = System.currentTimeMillis();
            Log.i(TAG, "video download beginning: " + videoUrl);

            //Open a connection to that URL.
            URLConnection ucon = url.openConnection();

            //this timeout affects how long it takes for the app to realize there's a connection problem
            ucon.setReadTimeout(TIMEOUT_CONNECTION);
            ucon.setConnectTimeout(TIMEOUT_SOCKET);


            //Define InputStreams to read from the URLConnection.
            // uses 3KB download buffer
            InputStream is = ucon.getInputStream();
            BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
            FileOutputStream outStream = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).toString()+"/new.mp4");
            byte[] buff = new byte[5 * 1024];

            //Read bytes (and store them) until there is nothing more to read(-1)
            int len;
            while ((len = inStream.read(buff)) != -1) {
                outStream.write(buff, 0, len);
            }

            //clean up
            outStream.flush();
            outStream.close();
            inStream.close();

            Log.i(TAG, "download completed in "
                    + ((System.currentTimeMillis() - startTime) / 1000)
                    + " sec");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {
        Log.v("TEST", result);
        dialog.dismiss();
    }
}

视频文件位于文件夹中。但是,当我试图在媒体播放器中播放它时,它不会播放。代码有什么问题吗?

0 个答案:

没有答案