android使用SoundPool 播放短音效

播放短音效

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;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章