8

如果我播放单个声音,它运行良好。

添加第二个声音会导致它崩溃。

有谁知道是什么导致了这个问题?

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);

您需要将第二行更改为:

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 回答