简体   繁体   中英

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.

You can play music using MediaPlayer as follows

MediaPlayer mp = MediaPlayer.create(this, idSong);
mp.start();

You can stop the music after 10 seconds by using a Timer as follows

new java.util.Timer().schedule(
    new java.util.TimerTask() {
        @Override
        public void run() {
            mp.pause();
        }
}, 10000);
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM