8

単一のサウンドを再生すると、正常に動作します。

2 番目のサウンドを追加すると、クラッシュします。

誰が問題の原因を知っていますか?

private SoundManager mSoundManager;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sos);

    mSoundManager = new SoundManager();
    mSoundManager.initSounds(getBaseContext());

    mSoundManager.addSound(1,R.raw.dit);
    mSoundManager.addSound(1,R.raw.dah);

    Button SoundButton = (Button)findViewById(R.id.SoundButton);
    SoundButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mSoundManager.playSound(1);
            mSoundManager.playSound(2);
        }
    });
}
4

1 に答える 1

14
 mSoundManager.addSound(1,R.raw.dit);
 mSoundManager.addSound(1,R.raw.dah);

2 行目を次のように変更する必要があります。

mSoundManager.addSound(2,R.raw.dah);

一度に複数のサウンドを再生するには、まず SoundPool にそれを知らせる必要があります。SoundPool の宣言で、20 ストリームを指定したことに注意してください。私のゲームには多くの銃や悪者が騒ぎ立てており、それぞれのサウンド ループは 3000 ミリ秒未満と非常に短いです。以下にサウンドを追加すると、「mAvailibleSounds」というベクトルで指定されたインデックスを追跡することに注意してください。このようにして、ゲームは存在しないアイテムのサウンドを試して再生し、クラッシュすることなく続行できます。この場合、各インデックスはスプライト ID に対応します。特定のサウンドを特定のスプライトにマッピングする方法を理解していただくために。

次に、playSound() でサウンドをキューに入れます。これが発生するたびに、soundId がスタックにドロップされ、タイムアウトが発生するたびにスタックがポップされます。これにより、再生後にストリームを強制終了し、再度再利用できます。私のゲームは非常にうるさいので、20 ストリームを選択します。その後、音が消えてしまうので、アプリケーションごとにマジックナンバーが必要になります。

私はこのソースをここで見つけ、runnable & kill キューを自分で追加しました。

private  SoundPool mSoundPool; 
 private  HashMap<Integer, Integer> mSoundPoolMap; 
 private  AudioManager  mAudioManager;
 private  Context mContext;
 private  Vector<Integer> mAvailibleSounds = new Vector<Integer>();
 private  Vector<Integer> mKillSoundQueue = new Vector<Integer>();
 private  Handler mHandler = new Handler();

 public SoundManager(){}

 public void initSounds(Context theContext) { 
   mContext = theContext;
      mSoundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0); 
      mSoundPoolMap = new HashMap<Integer, Integer>(); 
      mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);       
 } 

 public void addSound(int Index, int SoundID)
 {
  mAvailibleSounds.add(Index);
  mSoundPoolMap.put(Index, mSoundPool.load(mContext, SoundID, 1));

 }

 public void playSound(int index) { 
  // dont have a sound for this obj, return.
  if(mAvailibleSounds.contains(index)){

      int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
      int soundId = mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);

      mKillSoundQueue.add(soundId);

      // schedule the current sound to stop after set milliseconds
      mHandler.postDelayed(new Runnable() {
       public void run() {
        if(!mKillSoundQueue.isEmpty()){
         mSoundPool.stop(mKillSoundQueue.firstElement());
        }
          }
      }, 3000);
  }
 }
于 2010-09-21T20:01:59.637 に答える