Search code examples
javaandroidbackground-servicebackground-music

Play background music using timer in Android


In my application, there is 1 main activity and there are many fragments that are inflated by the activity.

In one of the fragments, there is a task that runs for 10 seconds. Along with this task, background music needs to be played for this duration.

How can I achieve this?

Any help will be appreciated.


Solution

  • private void startEverything() {
        startMyAnimation();
        playMusic()
    }
    
    private void startMyAnimation() {
        ObjectAnimator progressAnimator = ObjectAnimator.ofInt(mProgress, "progress", 0, 10000);
        progressAnimator.setDuration(10000);
        progressAnimator.setInterpolator(new LinearInterpolator());
        progressAnimator.start();
    }
    
    private void playMusic() {
        final MediaPlayer soundPlayer= MediaPlayer.create(getContext(), R.raw.your_bgm);
        soundPlayer.start();
    
    
        Handler musicStopHandler = new Handler();
        Runnable musicStopRunable = new Runnable() {
            @Override
            public void run() {
                soundPlayer.stop();
            }
        };
    
        musicStopHandler.postDelayed(musicStopRunable, 10000);
    }
    

    What happens here is, you start your animation by calling startMyAnimation(), then you call playMusic() to play your music.

    In playMusic(), you start playing the file by calling soundPlayer.start();, then you start run a Handler that will execute the code inside 'musicStopRunnable', and the code in musicStopRunnable, stops the music playing.

    reference : https://stackoverflow.com/a/18459304/4127441

    https://stackoverflow.com/a/1921759/4127441