Android使用URLConnection下載音頻文件的方法

使用MediaPlayer播放在線音頻,請參考Android MediaPlayer 播放音頻

網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)建站!專注于網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、微信小程序開發(fā)、集團企業(yè)網(wǎng)站建設(shè)等服務(wù)項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了鎮(zhèn)雄免費建站歡迎大家使用!

有時候我們會需要下載音頻文件。這里提供一種思路,將在線音頻文件通過流寫到本地文件中。

使用URLConnection來建立連接,獲取到的數(shù)據(jù)寫到文件中。

URLConnection建立連接后,可以獲取到數(shù)據(jù)長度。由此我們可以計算出下載進度。

 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();

值得注意的是,如果本地已經(jīng)有了文件,需要做一些邏輯判斷。例如是否刪掉舊文件,重新下載?;蚴桥袛喑鲆延形募兄勾舜蜗螺d任務(wù)。

例如可以用connection.getContentLength()與當前文件長度來比較,如果不一致,則刪掉本地文件,重新下載。

實際上,URLConnection能處理很多流媒體。在這里是用來下載音頻文件。可以實現(xiàn)下載功能和類似“邊下邊播”的功能。

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

總結(jié)

以上所述是小編給大家介紹的Android 使用URLConnection下載音頻文件的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對創(chuàng)新互聯(lián)網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!

當前題目:Android使用URLConnection下載音頻文件的方法
文章路徑:http://muchs.cn/article28/ihicjp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作標簽優(yōu)化、網(wǎng)站改版用戶體驗、小程序開發(fā)、營銷型網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

營銷型網(wǎng)站建設(shè)