随机音乐播放器在游戏中获胜

时间:2016-06-16 06:31:57

标签: android audio random soundmanager2

我制作小游戏,完成后会有音乐。现在我有一个声音,想要随机播放3个或4个,所以每次完成时你都会听到不同的音乐。 我有SoundManager.java,其中

public static final int SOUND_WINNER = 4;
public static final int SOUND_LOSER = 5;
public static final int SOUND_WINNER2 = 6;
public static final int SOUND_WINNER3 = 7;

以及

    public static void initSounds(Context theContext) { 
    mContext = theContext;
    mSoundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 0); 
    mSoundPoolMap = new HashMap<Integer, Integer>(); 
    loopedSoundMap = new HashMap<Integer, Integer>();
    mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);      

    addSound(SOUND_WINNER, R.raw.win);
    addSound(SOUND_LOSER, R.raw.lose);
    addSound(SOUND_WINNER2, R.raw.win2);
    addSound(SOUND_WINNER2, R.raw.win3);

在游戏活动中我把

    private void win(){ 
    SoundManager.playLoopedSound(SoundManager.SOUND_WINNER);

提前感谢任何建议。

我试图做这样的事但没有成功

private void win(){ 
    Random random=new Random();
    int r = random.nextInt(4);
    if(r==0){
    SoundManager.playLoopedSound(SoundManager.SOUND_WINNER);
    } 
    if(r==1){
    SoundManager.playLoopedSound(SoundManager.SOUND_WINNER2);
    } 

1 个答案:

答案 0 :(得分:0)

此方法适用于我playRaw(_this, R.raw.fail),它也适用于您。

private static void playRaw(Context _this, int resource) {
    PREFS = PreferenceManager.getDefaultSharedPreferences(_this);
    if (PREFS.getBoolean("SOUND_IN_GAME", true) == false) {
       return;
    }
    MediaPlayer mMediaPlayer = MediaPlayer.create(_this, resource);
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mMediaPlayer.setLooping(false);
    mMediaPlayer.start();
}

以下行可让您进行设置,以便关闭/开启声音。你可以删除它。

PREFS = PreferenceManager.getDefaultSharedPreferences(_this);
if (PREFS.getBoolean(Global.soundInMatch, true) == false) {
     return;
}

在您的情况下,您还可以打开循环标记

mMediaPlayer.setLooping(true);