android 背景音乐 及音效播放工具类
2016-05-27 13:52
507 查看
public class MusicPlayer implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener { private Context context; private MediaPlayer bgPlayer; //播放背景音乐的播放器 private SoundPool actionMusicPlayer; //播放音效的播放器 private int source_da,source_givecard,source_start,source_win,source_calllord; //各种音效的source public MusicPlayer(Context context) { //初始化 this.context = context; this.actionMusicPlayer = new SoundPool(10, AudioManager.STREAM_SYSTEM,5); //这里指定声音池的最大音频流数目为10,声音品质为5大家可以自己测试感受下效果 this.source_da = actionMusicPlayer.load(context, R.raw.da, 0); this.source_givecard = actionMusicPlayer.load(context, R.raw.givecard, 0); this.source_start = actionMusicPlayer.load(context, R.raw.start, 0); this.source_win = actionMusicPlayer.load(context, R.raw.win, 0); this.source_calllord = actionMusicPlayer.load(context, R.raw.calllord, 0); } public void onCompletion(MediaPlayer mp) { //音频文件播放完成时自动调用 } public boolean onError(MediaPlayer mp, int what, int extra) { //音频文件播放发生错误时自动调用 return false; } public void playBgSound(int paramInt) { //播放背景音乐,paramInt为音频文件ID if(!SysSetting.getInstance(context).isBgSound()) { //SysSetting为一个单例类,是我自己定义的,用于保存本应用程序相关设置,isBgSound()为得到是否开启背景音乐设置 return; } stopSound(bgPlayer); try { MediaPlayer mediaPlayer = MediaPlayer.create(context, paramInt); bgPlayer = mediaPlayer; bgPlayer.setOnCompletionListener(this); bgPlayer.setLooping(true); //设置是否循环,一般背景音乐都设为true bgPlayer.start(); } catch (IllegalStateException e) { e.printStackTrace(); } } public MediaPlayer getBackGroundPlayer() { return this.bgPlayer; } public void stopBgSound() { //停止背景音乐的播放 if(bgPlayer == null) return; if(bgPlayer.isPlaying()) bgPlayer.stop(); bgPlayer.release(); bgPlayer = null; } private void playSound(int source) { //如果系统设置中开启了音效,则播放相关的音频文件 if(SysSetting.getInstance(context).isEffectSound()) { actionMusicPlayer.play(source, 1, 1, 0, 0, 1); } } public void playHitCardSound() { playSound(source_da); } public void playGiveCardSound() { playSound(source_givecard); } public void playStartSound() { playSound(source_start); } public void playWinSound() { playSound(source_win); } public void playCalllordSound() { playSound(source_calllord); } }
可以考虑自己定义一个BaseActivity,继承BaseActivity,在其中定义一个静态的成员变量并在这个BaseActivity的onCreate方法中初始化该musicPlayer
相关文章推荐
- RxJava Rxandroid retrofit
- Android ShareSDK 修改分享功能展示界面
- Android 下载地址包含中文 无法下载的解决方法
- Android中View绘制流程以及invalidate()等相关方法分析
- Android读写NFC
- Android 传感器的使用
- 从Android运行时出发,打造我们的脱壳神器
- TextView部分文字变色、可点击。(微博话题 变色、点击)
- android 音乐播放工具类MediaPlayer
- Android传感器用法
- 解决AndroidStudio Cannot run program "git"(in directory) "F;\GitHubProiject.XXX" CreateProcess error=2
- Android按钮的四种点击事件
- AndroidStudio运行编译慢的提速方法
- Android使用源码中隐藏的API
- 通过回调在fragment中获取activity的触摸事件
- 静态代理,动态代理---笔记
- android studio快捷键
- 10分钟教你学会三级缓存
- 从头学android_Pull解析器解析xml文件
- android弹出框之Dialog