How Android uses URLConnection to download Audio Files
This article mainly shows you "Android how to use URLConnection to download audio files", the content is easy to understand, clear, hope to help you solve doubts, the following let the editor lead you to study and learn "Android how to use URLConnection to download audio files" this article.
Use MediaPlayer to play online audio. Please refer to Android MediaPlayer to play audio.
Sometimes we need to download audio files. Here is a way to stream an online audio file to a local file.
Use URLConnection to establish a connection and write the obtained data to a file.
After URLConnection establishes a connection, you can get the data length. 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 a file locally, you need to make some logical judgments. For example, whether to delete the old file and download it again. Or determine the existing files and abort the download task.
For example, connection.getContentLength () can be compared with the current file length, and if it is inconsistent, delete the local file and download it again.
In fact, URLConnection can handle a lot of streaming. Here is used to download audio files. It can realize the download function and similar "broadcast while playing" function.
The above is all the contents of the article "how to download audio files with Android using URLConnection". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!