2

我需要在活动运行时运行许多小声音。某些文件每隔固定时间间隔播放一次(例如 5 秒) 某些文件将在一个完成下一次启动时按顺序播放(例如 sound1、sound2、sound3)当触摸屏幕时。

总声音约为 35 个短 mp3 文件(最长 3 秒)。

实现这一点的最佳方法是什么?

谢谢

4

2 回答 2

2

SoundPool通常用于播放多个短声音。您可以在 onCreate() 中加载所有声音,将它们的位置存储在 HashMap 中。

创建声音池

public static final int SOUND_1 = 1;
public static final int SOUND_2 = 2;

SoundPool mSoundPool;
HashMap<Integer, Integer> mSoundMap;

@Override
public void onCreate(Bundle savedInstanceState){
  mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 100);
  mSoundMap = new HashMap<Integer, Integer>();

  if(mSoundPool != null){
    mSoundMap.put(SOUND_1, mSoundPool.load(this, R.raw.sound1, 1));
    mSoundMap.put(SOUND_2, mSoundPool.load(this, R.raw.sound2, 1));
  }
}

然后,当您需要播放声音时,只需调用 playSound() 并使用您的声音的常量值。

/*
*Call this function from code with the sound you want e.g. playSound(SOUND_1);
*/
public void playSound(int sound) {
    AudioManager mgr = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
    float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
    float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    float volume = streamVolumeCurrent / streamVolumeMax;  

    if(mSoundPool != null){
        mSoundPool.play(mSoundMap.get(sound), volume, volume, 1, 0, 1.0f);
    }
}
于 2012-07-07T16:03:13.647 回答
1

MediaPlayerPlaybackCompleted状态,所以当一个音频结束时,你可以开始播放另一个

public void setOnCompletionListener (MediaPlayer.OnCompletionListener listener)

来源

我会尝试ThreadAsyncTask分别播放不同的音频线

于 2012-07-07T12:40:53.403 回答