下面就来说说它的用法:
第一步:放置目标音频文件
将音频文件放在res/raw目录下,这样就可以通过R来引用它了。如果想放在Assert目录下也是可以的,这里先放在raw下。
第二步:编写音频播放的类
public class MusicPlayer { private Context mContext ; private static MusicPlayer sInstance ; static class Type{ public final static int MUSIC_CLICK = 1 ; public final static int MUSIC_FOCUSED = 2 ; } private SoundPool mSp ; private Map<Integer ,Integer> sSpMap ; private MusicPlayer(Context context){ mContext = context ; sSpMap = new TreeMap<Integer ,Integer>() ; mSp = new SoundPool(10 ,AudioManager.STREAM_MUSIC ,100) ; sSpMap.put(Type.MUSIC_CLICK, mSp.load(mContext, R.raw.click, 1)) ; sSpMap.put(Type.MUSIC_FOCUSED, mSp.load(mContext, R.raw.focused, 1)) ; } public static MusicPlayer getInstance(Context context){ if(sInstance == null) sInstance = new MusicPlayer(context) ; return sInstance ; } public void play(int type){ if(sSpMap.get(type) == null) return ; mSp.play(sSpMap.get(type), 1, 1, 0, 0, 1) ; } }
// 在界面上需要这样调用 // 初始化 mMusic = MusicPlayer.getInstance(MainActivity.this) ; // 在onClick中播放click时的声音 mMusic.play(MusicPlayer.Type.MUSIC_CLICK) ; // 在onFocusChange中聚焦状态播放聚焦的声音 mMusic.play(MusicPlayer.Type.MUSIC_FOCUSED) ;
MediaPlayer mMediaPlayer = new MediaPlayer() ; AssetFileDescriptor fd = mContext.getAssets().openFd(“music/click.pm3”) ; // assert目录下的music目录 mMediaPlayer.setDataSource(fd.getFileDescriptor() ,fd.getStartOffset() ,fd.getLength()) ; mMediaPlayer.prepare() ; mMediaPlayer.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer arg0) { mMediaPlayer.release() ; } }) ; mMediaPlayer.setOnErrorListener(new OnErrorListener() { @Override public boolean onError(MediaPlayer arg0, int arg1, int arg2) { mMediaPlayer.release() ; return false; } }) ; mMediaPlayer.start() ;
原文地址:http://blog.csdn.net/android_dong/article/details/42875651