Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

how to play audio file from server in android

I want to download audio file from url and play that audio file in my device.how to implement this concept in my application.please help me

Thanks Friends

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

to play audio file from server try this

  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
}

and if you want to download a .mp3 file form server then try this..

    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;
}

also in your manifest file use this permission..

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...