Android, how to play a song in 30 seconds only in mediaPlayer

I am working on Android, I am creating a player for audio songs. I want to play a song in just 30 seconds. After that, the player must be closed. It should start again if I press the START button again.

This is the code to create a media player:

  MediaPlayer mediaPlayer = new MediaPlayer(); public void songPreview(String songURL){ try{ mediaPlayer=new MediaPlayer(); mediaPlayer.setDataSource(songURL); mediaPlayer.prepare(); mediaPlayer.start(); } catch(Exception ex){ ex.printStackTrace(); } } 

Please suggest me which code should be used to play my song only for 30 seconds, after which it will stop, and if I want to play again, then I have to press the start button.

Note. Please provide me the logic to stop the media player after 30 seconds.

Thanks in advance.

+4
source share
3 answers

use countdownTimer to complete your task in which you can set a countdown timer up to 30 seconds manually. upon completion of the countdown process, it will go to the completion method and execute the completion method code:

  CountDownTimer cntr_aCounter = new CountDownTimer(3000, 1000) { public void onTick(long millisUntilFinished) { mp_xmPlayer2.start(); } public void onFinish() { //code fire after finish mp_xmPlayer2.stop(); } };cntr_aCounter.start(); 
+8
source
 private void playSoundForXSeconds(final Uri soundUri, int seconds) { if(soundUri!=null) { final MediaPlayer mp = new MediaPlayer(); try { mp.setDataSource(Settings.this, soundUri); mp.prepare(); mp.start(); }catch(Exception e) { e.printStackTrace(); } Handler mHandler = new Handler(); mHandler.postDelayed(new Runnable() { public void run() { try { mp.stop(); }catch(Exception e) { e.printStackTrace(); } } }, seconds * 1000); } } 
+4
source

This method jumps to the end of the track after the specified time has elapsed and allows the onCompleted built-in callback. You will obviously need to extend the code to handle any pause events that were triggered before playback ended.

  private static void startMedia(final MediaPlayer mediaPlayer, @Nullable Integer previewDuration) { mediaPlayer.start(); if( previewDuration != null) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mediaPlayer.seekTo(mediaPlayer.getDuration()); } }, previewDuration); } } 
0
source

All Articles