我用按钮和声音文件(mp3)创建简单的代码,
现在,当我按一下按钮时,声音文件正在播放,但是如果我按几次(快速),则只在第一次单击时播放,直到mp3结束...我希望每次单击都播放从一开始就发出声音。
public class TrafficLightsActivity extends Activity implements OnClickListener {
private ImageButton Upbutton ;
private ImageButton Downbutton ;
private ImageView Image ;
private MediaPlayer mp1 ;
private MediaPlayer mp2 ;
int counter=5 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.traffic_lights);
Upbutton = (ImageButton) findViewById (R.id.button1) ;
Downbutton = (ImageButton) findViewById (R.id.button2) ;
Image = (ImageView) findViewById(R.id.imageView1) ;
mp1 = MediaPlayer.create(this, R.raw.nextsound) ;
mp2 = MediaPlayer.create(this, R.raw.backsound) ;
Upbutton.setOnClickListener(this) ;
Downbutton.setOnClickListener(this) ; }
@Override
public void onClick(View v) {
if (Upbutton == v){
if (mp1.isPlaying()){
mp1.stop() ;
}
counter= counter+1 ;
System.out.println("Number of clicks is: " + counter) ;
mp1.start();
} }
最佳答案
您可以调用seekTo(0)
方法,该方法允许从头开始播放声音而无需结束声音:
if (Upbutton == v){
if(mp1.isPlaying())
mp1.seekTo(0);
mp1.start();
}