2012-09-29 23 views

回答

1

使用SoundPool類。將您的音頻文件放在/ res/raw /中,並首先加載它們(例如在OnCreate Method中),然後請求播放選定的音頻文件。這裏是代碼示例:

private SoundPool soundPool; 
private boolean tiltSoundsLoaded = false; 
private int tiltSoundID; 
private int tiltFailureSoundID; 

public void initTiltSounds(Context context) { 
    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); 

     soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() { 
    @Override 
     public void onLoadComplete(SoundPool soundPool, int sampleId, 
      int status) { 
      tiltSoundsLoaded = true; 
     } 
     }); 
     tiltSoundID = soundPool.load(context, R.raw.swosh_sound_effect, 1); 
     tiltFailureSoundID = soundPool.load(context, R.raw.fail_metallic, 1); 
} 

public void playTiltSound(AudioManager audioManager, boolean success) { 
    try{ 
     int soundToPlay; 
     if(success) 
      soundToPlay = tiltSoundID; 
     else 
      soundToPlay = tiltFailureSoundID; 

     float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
     if (tiltSoundsLoaded) 
      soundPool.play(soundToPlay, actualVolume, actualVolume, 1, 0, 1f); 
     else 
      Log.e(LOG_TAG, "Tilt Sound not loaded"); 
    }catch(Exception e){ 
      Log.e(LOG_TAG, "Could not play tilt sound"); 
    } 
}