Android Studio Mediaplayer how to fade in and out

前端 未结 3 2280
慢半拍i
慢半拍i 2021-02-20 17:08

I am working with the mediaplayer class in android studio. I simply want to fade out one sound and fade in the other sound instead of using setVolume(0,0) and setVolume(1,1).

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-20 17:28

    Looking at the linked example, you would have to call fadeIn()/fadeOut() in a loop, to increase/decrease the volume over a period of time. deltaTime would be the time between each iteration of the loop.

    You'd have to do this in a separate thread from your main UI thread, so you don't block it and cause your app to crash. You can do this by either putting this loop inside a new Thread/Runnable/Timer.

    Here is my example for fading in (you can do a similar thing for fading out):

    float volume = 0;
    
    private void startFadeIn(){
        final int FADE_DURATION = 3000; //The duration of the fade
        //The amount of time between volume changes. The smaller this is, the smoother the fade
        final int FADE_INTERVAL = 250;
        final int MAX_VOLUME = 1; //The volume will increase from 0 to 1
        int numberOfSteps = FADE_DURATION/FADE_INTERVAL; //Calculate the number of fade steps
        //Calculate by how much the volume changes each step
        final float deltaVolume = MAX_VOLUME / (float)numberOfSteps;
    
        //Create a new Timer and Timer task to run the fading outside the main UI thread
        final Timer timer = new Timer(true);
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                fadeInStep(deltaVolume); //Do a fade step
                //Cancel and Purge the Timer if the desired volume has been reached
                if(volume>=1f){
                    timer.cancel();
                    timer.purge();
                }
            }
        };
    
        timer.schedule(timerTask,FADE_INTERVAL,FADE_INTERVAL);
    }
    
    private void fadeInStep(float deltaVolume){
        mediaPlayer.setVolume(volume, volume);
        volume += deltaVolume;
    
    }
    

    Instead of using two separate MediaPlayer objects, I would in your case use just one and swap the track between the fades. Example:

    **Audio track #1 is playing but coming to the end**
    startFadeOut();
    mediaPlayer.stop();
    mediaPlayer.reset();
    mediaPlayer.setDataSource(context,audiofileUri);
    mediaPlayer.prepare();
    mediaPlayer.start();
    startFadeIn();
    **Audio track #2 has faded in and is now playing**
    

    Hope this solves your problem.

提交回复
热议问题