如何从URL链接下载音频文件?

时间:2019-08-03 15:03:43

标签: android

我正在创建一个应用程序,其中必须播放许多URL链接中的音频。在首次运行该应用程序时,我为用户提供了一次下载所有音频文件的选项。现在,我正在使用异步任务单独下载每个URL。这种方法的问题在于,因为我有6000个音频文件的url链接,所以需要很长时间。

我的问题是,有什么方法可以从6000个URL中快速下载音频文件。

下面,我还将提供用于下载每个URL的代码。

public class DownloadAudio extends AsyncTask<Void, Void, String> {

    public static final String TAG = DownloadAudio.class.getSimpleName();

    ProgressDialog mProgressDialog;

    Context context;
    String stringUrl;
    int index;

    public DownloadAudio(Context context,String url, int randomNumber) {
            this.context = context;

            stringUrl=url;

            index = randomNumber;

        }

        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(context, "Please wait", "Download …");
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {

                URL url = new URL(stringUrl);
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();
                String[] path = url.getPath().split("/");
                int temp = path.length - 1;
                String mp3 = path[temp];
                int lengthOfFile = c.getContentLength();

                String PATH = Environment.getExternalStorageDirectory()+ "/MyAudioApp/" ;
                Log.v(TAG, "PATH: " + PATH);
                File file = new File(PATH);
                file.mkdirs();

                String fileName = mp3;

                File outputFile = new File(file , fileName);


                FileOutputStream fos = new FileOutputStream(outputFile);

                InputStream is = c.getInputStream();

                byte[] buffer = new byte[1024];
                int len1 = 0;
                while ((len1 = is.read(buffer)) != -1) {

                    fos.write(buffer, 0, len1);
                }
                fos.close();
                is.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

        return "done";
    }

    protected void onPostExecute(String result) {
        if (result.equals("done")) {
            mProgressDialog.dismiss();
        }
    }

}

请提出任何建议将非常有帮助。

0 个答案:

没有答案