[英]how to play audio file from server in android
我想从url下载音频文件并在我的device.how中播放该音频文件,以便在我的应用程序中实现这个概念。请帮助我
谢谢朋友
从服务器播放音频文件试试这个
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>
尝试以下代码: -
private void PlayFile() {
try {
mp.reset();
Uri uri = Uri.parse("http://soundcloud.com/storynory/the-valentine-witch-mp3/download.mp3");
mp.setDataSource(this, uri); // "this" refers to context
mp.prepare();
mp.start();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
如果您需要“下载MP3”代码,那么我也会发布该代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.