SoFunction
Updated on 2025-04-12

Android How to download audio files using URLConnection

Use MediaPlayer to play online audio, please refer toAndroid MediaPlayer Plays audio

Sometimes we need to download audio files. Here is an idea to write online audio files to local files through streams.

Use URLConnection to establish a connection and write the obtained data to a file.

After the URLConnection is established, the data length can be obtained. From this we can calculate the download progress.

 public class DownloadStreamThread extends Thread {
  String urlStr;
  final String targetFileAbsPath;
  public DownloadStreamThread(String urlStr, String targetFileAbsPath) {
    = urlStr;
    = targetFileAbsPath;
  }
  @Override
  public void run() {
   ();
   int count;
   File targetFile = new File(targetFileAbsPath);
   try {
    boolean n = ();
    (TAG, "Create new file: " + n + ", " + targetFile);
   } catch (IOException e) {
    (TAG, "run: ", e);
   }
   try {
    URL url = new URL(urlStr);
    URLConnection connection = ();
    ();
    int contentLength = ();
    InputStream input = new BufferedInputStream(());
    OutputStream output = new FileOutputStream(targetFileAbsPath);
    byte[] buffer = new byte[1024];
    long total = 0;
    while ((count = (buffer)) != -1) {
     total += count;
     (TAG, (, "Download progress: %.2f%%", 100 * (total / (double) contentLength)));
     (buffer, 0, count);
    }
    ();
    ();
    ();
   } catch (Exception e) {
    (TAG, "run: ", e);
   }
  }
 }

Start the download, that is, start the thread.

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

It is worth noting that if there are files locally, some logical judgments are needed. For example, whether to delete the old file and download it again. Or determine that there is a file and terminate the download task.

For example, it can be used()Compare with the current file length. If it is inconsistent, delete the local file and download it again.

In fact, URLConnection can handle a lot of streaming media. This is used to download audio files. It can realize the download function and the functions similar to "playing at the bottom" one.

For the code, please refer to the sample project:/RustFisher/android-MediaPlayer

Summarize

The above is the method of using URLConnection to download audio files on Android. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!