播放短音效
1,准备资源文件(短音效文件)
在eclipse中,将准备好的声音文件放到res下的raw目录下(在res下新建一个文件名为raw的即可)
2,新建一个activity(包括两个Button),在activity中实现短音效的播放,如下:
声明SoundPool
1
2
|
private
SoundPool sp;
//得到一个声音池引用
private
HashMap<Integer,Integer> spMap;
//得到一个map的引用
|
onCreate(Bundle savedInstanceState) 中的代码:
1
2
3
4
5
6
|
initiSoundPool();
btn_shortmusic1 = (Button) findViewById(R.id.shortmusic1);
but_shortmusic2 = (Button) findViewById(R.id.shortmusic2);
btn_shortmusic1.setOnClickListener(
this
);
but_shortmusic2.setOnClickListener(
this
);
|
initiSoundPool();
1
2
3
4
5
6
7
|
public
void
initiSoundPool()
{
sp=
new
SoundPool(
4
, AudioManager.STREAM_MUSIC,
0
);
spMap=
new
HashMap<Integer, Integer>();
spMap.put(
1
, sp.load(
this
,R.raw.sound1,
1
));
spMap.put(
2
, sp.load(
this
,R.raw.sound2,
1
));
}
|
palySounds():
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public
void
playSound(
int
sound,
int
number){
//sound:播放音效的id,number:放音效的次数
AudioManager am=(AudioManager)
this
.getSystemService(
this
.AUDIO_SERVICE);
//实例化AudioManager对象
float
audioMaxVolumn=am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//返回当前AudioManager对象的最大音量值
float
audioCurrentVolumn=am.getStreamVolume(AudioManager.STREAM_MUSIC);
//返回当前AudioManager对象的音量值
float
volumnRatio=audioCurrentVolumn/audioMaxVolumn;
sp.play(
spMap.get(sound),
//播放的音乐id
volumnRatio,
//左声道音量
volumnRatio,
//右声道音量
1
,
//优先级,0为最低
number,
//循环次数,0无不循环,-1无永远循环
1
//回放速度 ,该值在0.5-2.0之间,1为正常速度
);
}
|
onClick(View arg0):
1
2
3
4
5
6
7
8
9
10
|
@Override
public
void
onClick(View arg0) {
// TODO Auto-generated method stub
switch
(arg0.getId()) {
case
R.id.shortmusic1:
playSound(
1
,
1
);
break
;
case
R.id.shortmusic2:
playSound(
2
,
1
);
break
;
|