android 背景音乐 及音效播放工具类

时间:2021-10-27 16:09:01
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