1. 程式人生 > >Android 使用URLConnection下載音訊檔案

Android 使用URLConnection下載音訊檔案

本文連結: Android 使用URLConnection下載音訊檔案

使用MediaPlayer播放線上音訊,請參考Android MediaPlayer 播放音訊

有時候我們會需要下載音訊檔案。這裡提供一種思路,將線上音訊檔案通過流寫到本地檔案中。
使用URLConnection來建立連線,獲取到的資料寫到檔案中。

URLConnection建立連線後,可以獲取到資料長度。由此我們可以計算出下載進度。

    public class DownloadStreamThread extends Thread {
        String urlStr;
        final String targetFileAbsPath;

        public DownloadStreamThread(String urlStr, String targetFileAbsPath) {
            this.urlStr = urlStr;
            this.targetFileAbsPath = targetFileAbsPath;
        }

        @Override
        public void run() {
            super.run();
            int count;
            File targetFile = new File(targetFileAbsPath);
            try {
                boolean n = targetFile.createNewFile();
                Log.d(TAG, "Create new file: " + n + ", " + targetFile);
            } catch (IOException e) {
                Log.e(TAG, "run: ", e);
            }
            try {
                URL url = new URL(urlStr);
                URLConnection connection = url.openConnection();
                connection.connect();
                int contentLength = connection.getContentLength();
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(targetFileAbsPath);

                byte[] buffer = new byte[1024];
                long total = 0;
                while ((count = input.read(buffer)) != -1) {
                    total += count;
                    Log.d(TAG, String.format(Locale.CHINA, "Download progress: %.2f%%", 100 * (total / (double) contentLength)));
                    output.write(buffer, 0, count);
                }
                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {
                Log.e(TAG, "run: ", e);
            }
        }
    }

啟動下載,即啟動執行緒。

new DownloadStreamThread(urlStr, targetFileAbsPath).start();

值得注意的是,如果本地已經有了檔案,需要做一些邏輯判斷。例如是否刪掉舊檔案,重新下載。或是判斷出已有檔案,中止此次下載任務。
例如可以用connection.getContentLength()與當前檔案長度來比較,如果不一致,則刪掉本地檔案,重新下載。

實際上,URLConnection能處理很多流媒體。在這裡是用來下載音訊檔案。可以實現下載功能和類似“邊下邊播”的功能。

程式碼可以參考示例工程: https://github.com/RustFisher/android-MediaPla