Playing audio for given amount of time in Android

1.6k views Asked by At

I am new to Android development.

In this application, I wanted an audio to play for certain duration (say 20 seconds). After 20sec it should not start to play. I used getDuration() method, but i didn't get what i need to.

Code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    Button button1=(Button)findViewById(R.id.button1);
    Button button2=(Button)findViewById(R.id.button2);
    button1.setOnClickListener(this);
    button2.setOnClickListener(this);
}

public void onClick(View v) {
    int resId;
    switch (v.getId()) {
    case R.id.button1:
        resId = R.raw.a;
        break;
    case R.id.button2:
        resId = R.raw.b;
        break;
    default:
        resId = R.raw.a;
        break;
    }
    // Release any resources from previous MediaPlayer
    if (mp != null) {
        mp.release();
    }

    mp = MediaPlayer.create(this, resId);
    mp.start();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
protected void onDestroy() {
    if(null!=mp){
        mp.release();
    }
    super.onDestroy();
}
1

There are 1 answers

0
Chandrakanth On BEST ANSWER

Try like this:

mp.start();
Handler handler=new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        mp.stop();
    }
}, 20 * 1000);

After 20 seconds, the audio will be stopped.