Method of Android Downloading Audio Files Using URLConnection

  • 2021-11-13 02:41:37
  • OfStack

Use MediaPlayer to play audio online, refer to Android MediaPlayer to play audio

Sometimes we need to download audio files. Here is an idea to stream online audio files to local files.

Use URLConnection to establish a connection, and the obtained data is written to a file.

After URLConnection establishes a connection, 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) {
   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);
   }
  }
 }

Start the download, that is, start the thread.


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

It is worth noting that if you already have files locally, you need to make some logical judgments. For example, whether to delete old files and download them again. Or judge the existing file and abort the download task.

For example, you can use connection.getContentLength() Compared with the current file length, if it is not 1, delete the local file and download it again.

In fact, URLConnection can handle a lot of streaming media. Here it is used to download audio files. It can realize download function and similar function of "playing while playing".

The code can refer to the sample project: https://github.com/RustFisher/android-MediaPlayer

Summarize


Related articles: