2011-09-16 47 views
4

我想從URL下載的音頻文件,並在我的device.how播放音頻文件,來實現播放音頻文件,這個概念在我application.please幫我如何從服務器中的Android

感謝網友

+0

[播放音頻文件](http://stackoverflow.com/search?q=android+play+audio+file)| [流音頻文件](http://stackoverflow.com/search?q=android+stream+audio) –

+0

@謝謝你的回覆,我需要播放音頻沒有下載。 – John

+0

@John:請看我的答案。 – user370305

回答

15

從服務器播放音頻文件試試這個

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

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

,如果你想下載一個MP3播放文件格式服務器,然後嘗試這個..

private class DownloadFile extends AsyncTask<String, Integer, String>{ 
    @Override 
    protected String doInBackground(String... url) { 
    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> 
1

試試下面的代碼: -

private void PlayFile() { 
    try { 
     mp.reset(); 
     Uri uri = "http://soundcloud.com/storynory/the-valentine-witch-mp3/download.mp3"; 
     mp.setDataSource(this, uri); 
     mp.prepare(); 
     mp.start(); 
    } catch (Exception e) { 
     // TODO: handle exception 
     e.printStackTrace(); 
    } 
} 

如果你被要求「下載MP3」的代碼,然後我會張貼代碼也。

+0

Uri!=字符串,請確認 –