這篇文章主要為大家展示了“Android如何使用URLConnection下載音頻文件”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“Android如何使用URLConnection下載音頻文件”這篇文章吧。
創新互聯專業為企業提供霞山網站建設、霞山做網站、霞山網站設計、霞山網站制作等企業網站建設、網頁設計與制作、霞山企業網站模板建站服務,十余年霞山做網站經驗,不只是建網站,更提供有價值的思路和整體網絡服務。
使用MediaPlayer播放在線音頻,請參考Android MediaPlayer 播放音頻
有時候我們會需要下載音頻文件。這里提供一種思路,將在線音頻文件通過流寫到本地文件中。
使用URLConnection來建立連接,獲取到的數據寫到文件中。
URLConnection建立連接后,可以獲取到數據長度。由此我們可以計算出下載進度。
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();
值得注意的是,如果本地已經有了文件,需要做一些邏輯判斷。例如是否刪掉舊文件,重新下載。或是判斷出已有文件,中止此次下載任務。
例如可以用connection.getContentLength()
與當前文件長度來比較,如果不一致,則刪掉本地文件,重新下載。
實際上,URLConnection能處理很多流媒體。在這里是用來下載音頻文件??梢詫崿F下載功能和類似“邊下邊播”的功能。
以上是“Android如何使用URLConnection下載音頻文件”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注創新互聯行業資訊頻道!
名稱欄目:Android如何使用URLConnection下載音頻文件
當前地址:http://www.2m8n56k.cn/article18/poocdp.html
成都網站建設公司_創新互聯,為您提供自適應網站、營銷型網站建設、網站建設、App設計、網站制作、定制開發
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:[email protected]。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯