最近在看Android多媒体相关的资料,发现在1.0-r2版本支持的音频格式amr、mp3、wav、mid,不支持aac格式,Android提供的MediaPlayer不支持类似J2me那样的流直接创建模式,而流创建显然是我们开发中最常用的模式,如我们到远程服务器下载音频、视频数据一般都是流的形式,如何使用流创建MediaPlayer呢?下面的代码是关于创建MediaPlayer的几种使用形式。
/**
* MedaiaPlayer的使用<br>
* <b>注意:</b>在实际的开发中要写一个后台服务(Service)来控制 #@see Android Source
* Music/src/com/android/music/MediaPlaybackService.java
*
* @author shenrenkui
*
*/
public class MediaPlayerDemo extends Activity {
private Button resButton;
private Button localFileButton;
private Button netUrlButton;
private Button streamButton;
private MediaPlayer mMediaPlayer;
private Context mContext;
public void on
super.on
mContext = this;
this.setContentView(R.layout.mediaplayerdemo);
resButton = (Button) this.findViewById(R.id.res);
localFileButton = (Button) this.findViewById(R.id.localFile);
netUrlButton = (Button) this.findViewById(R.id.netUrl);
streamButton = (Button) this.findViewById(R.id.stream);
resButton.setOnClickListener(buttonListener);
localFileButton.setOnClickListener(buttonListener);
netUrlButton.setOnClickListener(buttonListener);
streamButton.setOnClickListener(buttonListener);
}
/**
* Button事件响应接口
*/
private On
public void on
try {
if (resButton.equals(v)) {
releaseMediaPlayer();
mMediaPlayer = MediaPlayer.create(mContext,
R.raw.leave_out_all_the_rest);
mMediaPlayer.start();
} else if (localFileButton.equals(v)) {
Uri playUri = Uri.parse("/sdcard/download/mp3.mp3");
releaseMediaPlayer();
mMediaPlayer = MediaPlayer.create(mContext, playUri);
mMediaPlayer.start();
} else if (netUrlButton.equals(v)) {
releaseMediaPlayer();
//不得已而为之的办法
Uri playUri = Uri
.parse("http://music.isohuo.com/2282/a3dca6eabba74bbd8c46b23e6dddfe43.mp3");
mMediaPlayer = MediaPlayer.create(mContext, playUri);
mMediaPlayer.start();
} else if (streamButton.equals(v)) {
releaseMediaPlayer();
mMediaPlayer = create(mContext,
R.raw.leave_out_all_the_rest);
mMediaPlayer.start();
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
};
private MediaPlayer create(Context context, int resid) {
InputStream stream = context.getResources().openRawResource(resid);
if (stream != null)
return create(context, stream);
else
return null;
}
private MediaPlayer create(Context context, InputStream stream) {
MediaPlayer mediaplayer = null;
try {
File temp = File.createTempFile("mediaplayertmp", "temp");
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
//用BufferdOutputStream速度快
BufferedOutputStream bis = new BufferedOutputStream(out);
byte buf[] = new byte[128];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
bis.write(buf, 0, numread);
} while (true);
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(tempPath);
mp.prepare();
mediaplayer = mp;
} catch (Exception e) {
e.printStackTrace();
}
return mediaplayer;
}
/**
* 释放上一次MediaPlayer资源
*/
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.release();
mMediaPlayer = null;
}
}
}