【问题标题】:Playing multiple sounds using SoundManager使用 SoundManager 播放多个声音
【发布时间】:2010-06-14 16:42:38
【问题描述】:

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

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

有人知道是什么原因造成的吗?

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

【问题讨论】:

  • 导致它崩溃的异常是什么?堆栈跟踪?

标签: android audio soundpool


【解决方案1】:
 mSoundManager.addSound(1,R.raw.dit);
 mSoundManager.addSound(1,R.raw.dah);

你需要把第二行改成:

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

为了一次播放多个声音,首先您需要让 SoundPool 知道这一点。在 SoundPool 的声明中,我指定了 20 个流。我的游戏中有很多枪和坏人在制造噪音,每个都有一个非常短的声音循环,

接下来,我们使用 playSound() 对声音进行排队。每次发生这种情况时,都会将 soundId 放入堆栈中,然后在发生超时时弹出堆栈。这使我可以在播放完流后将其杀死,然后再次重用它。我选择 20 个流,因为我的游戏非常嘈杂。在那之后,声音被洗掉了,所以每个应用程序都需要一个幻数。

我找到了这个来源here,并自己添加了可运行和终止队列。

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

【讨论】:

  • 我注意到这种方法有时会导致微滞后。当我一个接一个地播放一组短音时,这一点很明显。会是什么?
猜你喜欢
  • 2011-08-12
  • 1970-01-01
  • 1970-01-01
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多