2011-09-15 94 views
1

我想創建一個應用程序,可以從服務器上精確下載音樂文件.mp3,因爲我是Android開發領域的新手,所以我會很感激任何幫助來自你們。 我需要一些東西開始,我會很感激,如果你能給我一些有用的資源鏈接。 感謝從android下載一個mp3文件

回答

2

你能做到這樣::

  try { 
        MediaPlayer player = new MediaPlayer(); 
     player.setAudioStreamType(AudioManager.STREAM_MUSIC); 
     player.setDataSource("http://xty/MRESC/images/test/xy.mp3" 
       ); 
     player.prepare(); 
        player.star(); 

    } catch (Exception e) { 
     // TODO: handle exception 
    } 

清單權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> 
<uses-permission android:name="android.permission.INTERNET"></uses-permission> 
+0

Thanx nik ..我想下載MP3文件,代碼是給玩家的。 – clayforbrick

+3

雖然你的代碼的作品,OP要求下載,而不是流 – Jimmar

11

如果你想從任何URL播放MP3檔案,然後按照代碼由nik建議。

但是,如果你想下載一個文件形成的服務器,並將其存儲在SD卡或內部存儲設備的任何地方,那麼按照這個代碼,

private class DownloadFile extends AsyncTask<String, Integer, String>{ 
@Override 
protected String doInBackground(String... urlParams) { 
    int count; 
    try { 
     URL url = new URL("url of your .mp3 file"); 
     URLConnection conexion = url.openConnection(); 
     conexion.connect(); 
     // this will be useful so that you can show a tipical 0-100% progress bar 
     int lenghtOfFile = conexion.getContentLength(); 

     // downlod the file 
     InputStream input = new BufferedInputStream(url.openStream()); 
     OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.mp3"); 

     byte data[] = new byte[1024]; 

     long total = 0; 

     while ((count = input.read(data)) != -1) { 
      total += count; 
      // publishing the progress.... 
      publishProgress((int)(total*100/lenghtOfFile)); 
      output.write(data, 0, count); 
     } 

     output.flush(); 
     output.close(); 
     input.close(); 
    } catch (Exception e) {} 
    return null; 
} 

編輯:清單權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> 

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 
+0

thanx的代碼,但即時通訊仍然有問題,因爲我仍然不知道如何動態輸入輸入。我的意思是當用戶複製並粘貼鏈接文本框,然後應用程序應該開始從該網站下載文件。 – clayforbrick

+0

@clayforbrick - 當用戶複製 - 將鏈接粘貼到編輯文本框中時,只需獲取該編輯文本並將其傳遞給下載文件URL url = new URL(「.mp3文件的URL,您要下載」));如果是用於保存文件,則將其傳遞給OutputStream output = new FileOutputStream(「/ sdcard/somewhere/nameofthefile saving file.mp3」); – user370305

+0

如果你發現這對你是正確的,那麼請接受這個答案。謝謝:-) – user370305