溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時(shí)間:2020-09-22 01:38:02 來(lái)源:腳本之家 閱讀:126 作者:返回主頁(yè) RF-Dev 欄目:移動(dòng)開(kāi)發(fā)

使用MediaPlayer播放在線音頻,請(qǐng)參考Android MediaPlayer 播放音頻

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

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

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

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

啟動(dòng)下載,即啟動(dòng)線程。

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

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

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

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

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

總結(jié)

以上所述是小編給大家介紹的Android 使用URLConnection下載音頻文件的方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI