如何使ImageButton在每次单击时重复声音

时间:2017-03-11 23:29:23

标签: android audio imagebutton playback

我试图让图像按钮在每次点击时播放声音。例如,如果声音播放几秒钟,我再次按下按钮,它应该从头开始。我设法使声音工作,但它没有重复它。我怎样才能重新开始呢?

ImageButton bt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bt = (ImageButton) findViewById(R.id.clickme);
    final MediaPlayer mp = MediaPlayer.create(this, R.raw.bird);
    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mp.start();
        }
    });
}

2 个答案:

答案 0 :(得分:1)

试试这个:

@Override
public void onClick(View v) {
    try {
        if (mp.isPlaying()) {
            mp.stop();
            mp.release();
            mp = MediaPlayer.create(context, R.raw.bird);
        }
        mp.start();
    } catch(Exception e) { 
        e.printStackTrace(); 
    }
}

答案 1 :(得分:0)

使用MediaPlayer.seekto()寻找音频文件的开头。

ImageButton bt;
private MediaPlayer mp = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bt = (ImageButton) findViewById(R.id.clickme);
    mp = MediaPlayer.create(this, R.raw.bird);
    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(mp.isPlaying()) {
                 mp.seekTo(0);
            } else {
                 mp.start();
            }
        }
    });
}