我正在尝试播放mp3文件(带有onClickListener)并在2秒后停止。我尝试了下面的代码,但无法正常工作。谁能帮忙吗?
final MediaPlayer mpsound = MediaPlayer.create(this, R.raw.media_player_sound);
ImageView sound = (ImageView) findViewById(R.id.button);
sound.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mpsound.start();{
sleep(2000);
mpsound.stop();
}
}
});
最佳答案
如果使用mpsound播放音频,为什么要在mpfrog上调用stop()?您需要在mpsound MediaPlayer上调用stop()函数。另外,您可能希望将@Override批注添加到onClick()方法。
对于覆盖...
sound.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mpsound.start();{
sleep(2000);
mpsound.stop();
}
}
});
计时器.....
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg){
mpsound.stop();
}
};
//Task for timer to execute when time expires
class SleepTask extends TimerTask {
@Override
public void run(){
handler.sendEmptyMessage(0);
}
}
//then in some other function...
Timer timer = new Timer("timer",true);
timer.schedule(new SleepTask(),2000);