如何使用soundPool在按钮点击时播放短音?

时间:2012-12-30 10:01:51

标签: android button soundpool

我有5个按钮。我想在每次点击按钮时播放短音。每个按钮将播放与原始文件夹不同的声音。目前,我可以从第一个按钮播放声音,但如何在不创建大量代码的情况下从另一个按钮分配声音?请。帮助

到目前为止,这是我的代码:

public class Alphabet extends Activity {
private Button a, b, c, d, e;
    private SoundPool spool;
    private int soundID;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.alphabet);

    Button a = (Button) findViewById(R.id.a);
    Button b = (Button) findViewById(R.id.b);
    Button c = (Button) findViewById(R.id.c);
    Button d = (Button) findViewById(R.id.d);
    Button e = (Button) findViewById(R.id.e);



    a.setOnClickListener(new OnClickListener() 
    { 
          public void onClick(View v) { 
          Sound(); 
          } 
     });

    b.setOnClickListener(new OnClickListener() 
    { 
          public void onClick(View v) { 
          Sound(); 
          } 
     });

    c.setOnClickListener(new OnClickListener() 
    { 
          public void onClick(View v) { 
          Sound(); 
          } 
     });

    d.setOnClickListener(new OnClickListener() 
    { 
          public void onClick(View v) { 
          Sound(); 
          } 
     });

    e.setOnClickListener(new OnClickListener() 
    { 
          public void onClick(View v) { 
          Sound(); 
          } 
     });

    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    spool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    soundID = spool.load(this, R.raw.a, 1);


}
public void Sound(){
    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    float volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    android.util.Log.v("SOUND","["+volume+"]["+spool.play(soundID, volume, volume, 1, 0, 1f)+"]");
};

}

1 个答案:

答案 0 :(得分:-1)

例如,您可以将参数设置为您的Sound()方法,如

    Sound(int soundID){

      spool.load(this, soundID)
      AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
      float volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    }

将声音从onClick中的原始文件夹放入方法:

    public void onClick(View v) { 
      Sound(R.raw.a,1); //put the sounds as parameter
      }