如何在android中从服务器播放音频文件

Joh*_*ohn 5 android

我想从url下载音频文件并在我的device.how中播放该音频文件,以便在我的应用程序中实现这个概念.请帮助我

谢谢朋友

use*_*305 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
}
Run Code Online (Sandbox Code Playgroud)

如果你想下载.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;
}
Run Code Online (Sandbox Code Playgroud)

也在您的清单文件中使用此权限..

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

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Run Code Online (Sandbox Code Playgroud)