如何从音频网址下载前10秒的音频

时间:2019-08-20 11:42:21

标签: android file fileoutputstream urlconnection

我正在控制doInBackground中下载文件的进度,但是无法从FileOutputStream中的AsyncTask获取下载的音频数据播放持续时间。要求是“仅从音频URL下载10秒音频”。还有其他方法或库(依赖项)吗?

private class DownloadFile extends AsyncTask<String, String, String> {
    private ProgressDialog progressDialog;
    private String fileName;
    private String folder;
    private boolean isDownloaded;

    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection connection = url.openConnection();
            connection.connect();
            // getting file length
            int lengthOfFile = connection.getContentLength();
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            String timestamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());


            fileName = f_url[0].substring(f_url[0].lastIndexOf('/') + 1, f_url[0].length());

            //Append timestamp to file name
            fileName = timestamp + "_" + fileName;

            //External directory path to save file
            folder = Environment.getExternalStorageDirectory() + File.separator + "my_downloaded/";

            //Create androiddeft folder if it does not exist
            File directory = new File(folder);

            if (!directory.exists()) {
                directory.mkdirs();
            }

            OutputStream output = new FileOutputStream(folder + fileName);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;

                output.write(data, 0, count);
                if ( (int) ((total * 100) / lengthOfFile)>=4){
                    output.flush();

                    output.close();
                    input.close();
                    return "Downloaded at: " + folder + fileName;
                }
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();
            return "Downloaded at: " + folder + fileName;

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return "Something went wrong";
    }

    @Override
    protected void onPostExecute(String message) {
        // dismiss the dialog after the file was downloaded
        this.progressDialog.dismiss();
    }
}

0 个答案:

没有答案