2014-01-11 51 views
0

我在我的Android應用程序中有一個SoundPool,但我不知道如何編寫2個或更多SoundPool實例的代碼。有沒有辦法爲多個SoundPools修改此代碼?如何創建多個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; 
} 
+0

@Joel你能幫助我嗎? –

回答

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播放聲音。

希望這有助於即使有點晚了!)