Android多媒体开发--资源文件播放
播放音频文件。按照音频文件来源不同可以分为:资源文件播放、系统播放文件和网络文件播放。
资源文件播放是放在“<工程>/res/raw”,然后发布的时候被打成APK包一起安装在手机上。很显然这种方式不适合用于播放娱乐为主的多媒体文件,由于娱乐的多媒体文件是经常更新的,而放置在这个raw下面的文件用户是没有权限更新的,因此这种方式一般用于应用自己的一些音频和视频播放,如按键音、开机启动音、信息提示音等应用使用的声音。
下面看看播放资源音频文件的代码请参考代码清单12-1,完整代码请参考Chapter12_1工程中AudioPlayer代码部分。
【代码清单12-1】
public class AudioPlayer extends Activity {private ImageButton play;private ImageButton stop;private MediaPlayer mMediaPlayer;private int state = IDLE;private static final int PLAYING = 0;private static final int PAUSE = 1;private static final int STOP = 2;private static final int IDLE = 3;public static final int UPDATE = 2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.audio_player);// 初始化播放按钮play = (ImageButton) findViewById(R.id.play);play.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {if (state == PLAYING) {pause();} else {start();}}});// 初始化停止按钮stop = (ImageButton) findViewById(R.id.stop);stop.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {stop();}});// 开始播放歌曲play();}private void pause() {if (mMediaPlayer.isPlaying()) {mMediaPlayer.pause();state = PAUSE;}play.setImageResource(R.drawable.play);}private void start() {if (state == STOP) {play();} else if (state == PAUSE) {mMediaPlayer.start();state = PLAYING;}play.setImageResource(R.drawable.pause);}private void stop() {mMediaPlayer.stop();state = STOP;play.setImageResource(R.drawable.play);}// MediaPlayer进入prepared状态开始播放private OnPreparedListener preListener = new OnPreparedListener() {public void onPrepared(MediaPlayer arg0) {mMediaPlayer.start();state = PLAYING;}};private void play() {try {if (mMediaPlayer == null || state == STOP) {// 创建MediaPlayer对象并设置ListenermMediaPlayer = MediaPlayer.create(this, R.raw.ma_mma);mMediaPlayer.setOnPreparedListener(preListener);} else {// 复用MediaPlayer对象mMediaPlayer.reset();}} catch (Exception e) {e.printStackTrace();}}}
private void play() {try {if (mMediaPlayer == null || state == STOP) {// 创建MediaPlayer对象并设置ListenermMediaPlayer = MediaPlayer.create(this, R.raw.ma_mma);mMediaPlayer.setOnPreparedListener(preListener);} else {// 复用MediaPlayer对象mMediaPlayer.reset();}} catch (Exception e) {e.printStackTrace();}}
private OnPreparedListener preListener = new OnPreparedListener() {public void onPrepared(MediaPlayer arg0) {mMediaPlayer.start();state = PLAYING;}};
private void pause() {if (mMediaPlayer.isPlaying()) {mMediaPlayer.pause();state = PAUSE;}play.setImageResource(R.drawable.play);}
private void stop() {mMediaPlayer.stop();state = STOP;play.setImageResource(R.drawable.play);}