音效
res文件夹下创建raw,将要播放的音效文件放入
通过Map来匹配这些音效
代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59public class SoundPlayerManager {
private SoundPool mSoundPlayer;
private Map<Integer,Integer> mSoundMap;
private Context mContext;
public static SoundPlayerManager mInstance;
private SoundPlayerManager(Context context)
{
mContext = context;
}
public static SoundPlayerManager getInstance(Context context) {
if (mInstance == null) {
synchronized (SoundPlayerManager.class) {
if (mInstance == null)
mInstance = new SoundPlayerManager(context);
}
}
return mInstance;
}
/**
* 初始化
*
*/
public void init() {
mSoundMap = new HashMap<Integer, Integer>();
mSoundPlayer = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
mSoundMap.put(Constant.SOUND_WINDOW, mSoundPlayer.load(mContext,R.raw.window_openandclose,1));
mSoundMap.put(Constant.SOUND_CLICK, mSoundPlayer.load(mContext,R.raw.button_click,1));
mSoundMap.put(Constant.SOUND_SIGN, mSoundPlayer.load(mContext,R.raw.sign,1));
mSoundMap.put(Constant.SOUND_GAIN, mSoundPlayer.load(mContext,R.raw.treasure_gain,1));
mSoundMap.put(Constant.SOUND_GAME_START, mSoundPlayer.load(mContext,R.raw.game_start,1));
}
/**
* 播放声音
*
* @param soundKey
*/
public void play(int soundKey) {
AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
//最大音量
float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
//当前音量
float audioCurrentVolumn = am.getStreamVolume(AudioManager.STREAM_SYSTEM);
float volumnRatio = audioCurrentVolumn/audioMaxVolumn;
/**
* @param soundID a soundID returned by the load() function
* @param leftVolume left volume value (range = 0.0 to 1.0)
* @param rightVolume right volume value (range = 0.0 to 1.0)
* @param priority stream priority (0 = lowest priority)
* @param loop loop mode (0 = no loop, -1 = loop forever)
* @param rate playback rate (1.0 = normal playback, range 0.5 to 2.0)
*/
mSoundPlayer.play(mSoundMap.get(soundKey), volumnRatio, volumnRatio, 1, 0, 1);
}
}
在合适的地方初始化,如application里面,1
2//初始化soundplay
SoundPlayerManager.getInstance(GwApplication.getGwApplication()).init();
调用的时候 SoundPlayerManager.getInstance(GwApplication.getGwApplication()).play(Constant.SOUND_CLICK);
背景音乐
音乐播放器有很多功能,播放背景音乐只需要简单的功能就可以
1 | public class MediaPlayerManager { |