Android - 在每次按键点击时从头开始播放相同的声音

时间:2015-04-29 06:56:20

标签: android button

我使用按钮和声音文件(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();


        }   }

2 个答案:

答案 0 :(得分:1)

你可以调用seekTo(0)方法,让你在不完成声音的情况下重播声音:

if (Upbutton == v){
        if(mp1.isPlaying())
            mp1.seekTo(0);
        mp1.start();
    } 

答案 1 :(得分:0)

试试这种方式

var calendarSetupObject = {
                inputField  : "' . $this->getId() . '",
                ifFormat: "%Y-%m-%e %H:%M:%S", //changed line
                showsTime: true,               //changed line
                button      : "' . $this->getId() . '_trig",
                align       : "Bl",
                singleClick : true,