Fork me on GitHub

Android MediaPlayer

import android.media.MediaPlayer;
import android.media.MediaPlayer.*;

private MediaPlayer mediaPlayer;

OnCreate:

mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.stop();
mediaPlayer.release();
}
});


mediaPlayer.setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
mediaPlayer.release();
return true;
}
});

mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});

try {
String path = Environment.getExternalStorageDirectory().getPath().concat("/com.buzz.exhibition/audio/a.mp3");
//Log.i(TAG, path);
mediaPlayer.reset();
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
} catch (Exception ex) {
Log.i(TAG, ex.toString());
}

onDestroy:

mediaPlayer.release();

 Ref:Android开发指南(34) —— Multimedia and Camera - Media Playback

 Ref:Android AudioManager获取媒体焦点

 Ref:Android中的Audio播放:竞争Audio之Audio Focus的应用

 Ref:Android MediaPlayer的生命周期

posted @ 2015-03-06 13:58  Nick.Chung  阅读(256)  评论(0编辑  收藏  举报