Android how can play song for 30 seconds only in mediaPlayer

后端 未结 3 1206
迷失自我
迷失自我 2021-01-18 05:27

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

相关标签:
3条回答
  • 2021-01-18 05:44
    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-18 05:46

    This method jumps to the end of the track after a given time and allows the native onCompleted callback do its work. You'd obviously need to expand the code to handle any pause events fired before the playback completes.

        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 讨论(0)
  • 2021-01-18 05:57

    use countdownTimer to complete your goal in which you can set countdown timer till 30 second manually. when countdown finish process it will go to finish method and execute finish 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();
    
    0 讨论(0)
提交回复
热议问题