从原始文件夹播放随机声音

时间:2014-02-12 18:51:25

标签: java android eclipse random soundpool

我现在有一个SoundPool可以在屏幕震动时加载并播放一个声音,每次屏幕震动时我怎么会播放不同的声音呢?

编辑---

private SensorManager mSensorManager;
private ShakeEventListener mSensorListener;
SoundPool sp;
int soundOne;
int soundTwo;
int soundThree;

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    //Shake sound
    sp =  new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
    soundOne = sp.load(this, R.raw.one, 1);
    soundTwo = sp.load(this, R.raw.two, 1);
    soundThree = sp.load(this, R.raw.three, 1);     

    //Shake
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mSensorListener = new ShakeEventListener();   
    mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {

        public void onShake() {
            if (acceptCheck == 1)
            {
                sp.play(soundOne, 1, 1, 0, 0, 1);
            }
        }
      });




}

2 个答案:

答案 0 :(得分:3)

只需使用整数列表,而不是单独存储它们:

private SensorManager mSensorManager;
private ShakeEventListener mSensorListener;
SoundPool sp;
List<Integer> mSounds = new ArrayList<Integer>();
private Random mRandom = new Random();

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    //Shake sound
    sp =  new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
    mSounds.add(sp.load(this, R.raw.one, 1));
    mSounds.add(sp.load(this, R.raw.two, 1));
    mSounds.add(sp.load(this, R.raw.three, 1);     

    //Shake
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mSensorListener = new ShakeEventListener();   
    mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {

        public void onShake() {
            if (acceptCheck == 1)
            {
                sp.play(mSounds.get(mRandom.nextInt(mSounds.size())), 1, 1, 0, 0, 1);
            }
        }
      });
}

答案 1 :(得分:1)

首先,您可以使用所有原始引用创建一个数组:

private int[] rawRef = {R.raw.1,R.raw.2,R.raw.3,R.raw.4,R.raw.5};

然后你需要一种播放音频的方法:

private Random random = new Random();

private void play() {
   MediaPlayer mp;
   try {
      mp = MediaPlayer.create(this, rawRef[random.nextInt(rawRef.length)]);
      mp.start();
   } catch (Exception e) {
      Log.e("ERROR", "Media Player", e);
      mp = null;
   }
}

对于SoundPool

    private List pool = new ArrayList();
    private SoundPool sp;

    private void loadSounds(){
       sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
       pool.add(sp.load(context, R.raw.1, 1));
       pool.add(sp.load(context, R.raw.2, 1));
       pool.add(sp.load(context, R.raw.3, 1));
       pool.add(sp.load(context, R.raw.4, 1));
    }

    private void play(){
       sp.play(pool.get(random.nextInt(pool.size()), 1, 1, 0, 0, 1);
    }