Android - Interchange通过计时器发出声音

时间:2017-04-12 12:56:55

标签: android

我有一个链接到计时器的按钮,每500毫秒播放一个给定的声音。这是按预期工作的,但我希望它在每第4个循环播放不同的声音:

  

sound1 sound1 sound1 sound2 sound1 sound1 sound1 sound2 等。

有没有人知道这样做的正确方法?

final MediaPlayer sound1 = MediaPlayer.create(this, R.raw.snd1);
final MediaPlayer sound2 = MediaPlayer.create(this, R.raw.snd2);

Button play = (Button)findViewById(R.id.button1);

play.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Timer timer = new Timer("click", true);
        TimerTask tone = new TimerTask(){
            @Override
            public void run(){
                sound1.start();
            }
        };
        timer.scheduleAtFixedRate(tone, 500, 500);
    }
 });

2 个答案:

答案 0 :(得分:1)

你在这里:

final MediaPlayer sound1 = MediaPlayer.create(this, R.raw.snd1);
final MediaPlayer sound2 = MediaPlayer.create(this, R.raw.snd2);
int sound = 1;
Button play = (Button)findViewById(R.id.button1);

play.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Timer timer = new Timer("click", true);
        TimerTask tone = new TimerTask(){
            @Override
            public void run(){
                if (sound % 4 != 0){
                sound1.start();
                sound += 1;
                }else{
                sound2.start();
                sound = 1;
            }
        };
        timer.scheduleAtFixedRate(tone, 500, 500);
    }
});

答案 1 :(得分:0)

在你的主题中:

if(count / 4 == 1){
    playSound2();
    count = 1;
}else{
    playSound1();
    count++;
}

count是您在班级中声明的变量:

int count = 1;

当您需要停止时,请务必重置count