如何创建多个Soundpool?

时间:2014-01-11 18:16:01

标签: android soundpool

我的Android应用中有一个SoundPool,但我不知道如何编写2个或更多SoundPool个实例的代码。有没有办法为多个SoundPools重做这段代码?

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    View view = findViewById(R.id.button1);
    view.setOnTouchListener(this);

    // Set the hardware buttons to control the music
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    // Load the sound
    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener()

    {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId,
                int status) {
            loaded = true;

        }
    });

    soundID = soundPool.load(this, R.raw.sound1, 1);

}
public boolean onTouch( View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        // Getting the user sound settings
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        float actualVolume = (float) audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC);
        float maxVolume = (float) audioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float volume = actualVolume / maxVolume;
        // Is the sound loaded already?
        if (loaded) {
            soundPool.play(soundID, volume, volume, 1, 0, 1f);
            Log.e("Test", "Played sound");
        }
    }
    return false;
}

1 个答案:

答案 0 :(得分:1)

尝试:

// 8 soundpools
SoundPool[] soundPool = new SoundPool[8];
int[] soundID = new int[8];

// You can have more that one set per sound if need, just make more raw sound 
// arrays with different sounds.

// 8 sounds per soundpool
int[] rawSounds = new int[]{ R.id.sound1, R.id.sound2, R.id.sound3,
                             R.id.sound4, R.id.sound5, R.id.sound6,
                             R.id.sound7, R.id.sound8 };

boolean[] loaded = new boolean[8];

// Go through each soundpool
for(int i = 0; i < 8; i++)
{
    soundPool[i] = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

    // 8 sounds in one soundpool
    for(int h = 0; h < 8; h++)
    {
        soundID[i] = soundPool.load(this, rawSounds[i], 1); 
    }

    soundPool[i].setOnLoadCompleteListener(new OnLoadCompleteListener()
    {
        Override
        public void onLoadComplete(SoundPool soundPool, int sampleId,
                int status) 
        {
            // One boolean per soundpool
            loaded[i] = true;
        }
    });
}

然后使用for循环查看正在按什么声音,并使用soundID [i] .play播放声音。

希望这有点帮助,即使有点晚了!)